单击时禁用JButton并在1秒后重新启用它?

Fac*_*ted 2 java swing

我需要在点击时禁用JButton并在2秒后再次启用它,所以我已经尝试从事件处理程序中休眠ui线程,但这使得按钮处于选中状态,您无法读取该文本禁用按钮.

代码看起来像这样:

JButton button = new JButton("Press me");
button.addActionListener(new ActionListener{
    public void actionPerformed(ActionEvent ae) {
        JButton button = ((JButton)e.getSource());
        button.setEnabled(false);
        button.setText("Wait a second")
        button.repaint();
        try {
           Thread.sleep(2000);
        } catch (InterruptedException ie) {
        }
        button.setEnabled(true);
        button.setText("");
    }
Run Code Online (Sandbox Code Playgroud)

发生的事情是按钮保持在"被选中"状态,2秒没有文本,并立即禁用并重新启用按钮,这不是我想要的,我的目标是按钮保持禁用状态,并在其上显示文本两秒钟,然后重新启用.

我该怎么办?

cle*_*ght 5

正如user2864740指出的那样 - " 不要在UI线程上使用Thread.sleep(UI"冻结"并且没有机会重新绘制).使用Timer类. "

这是他所指的那种事的一个例子.应该接近你想做的事情:

JButton button = new JButton("Press me");
int delay = 2000; //milliseconds
Timer timer = new Timer(delay, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        button.setEnabled(true);
        button.setText("");
    }
});
timer.setRepeats(false);
button.addActionListener(new ActionListener {
    public void actionPerformed(ActionEvent ae) {
        JButton button = ((JButton)e.getSource());
        button.setEnabled(false);
        button.setText("Wait a second")
        timer.start();
    }
}
Run Code Online (Sandbox Code Playgroud)