我需要在单击时禁用 JButton 并在 2 秒后再次启用它,因此我尝试从事件处理程序中 hibernate 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("");
}
发生的情况是按钮保持在“被选择”状态,2秒内没有任何文本,最后立即禁用并重新启用按钮,这不是我想要的,也不是我的目标是保持禁用状态并带有文本的按钮两秒钟,然后重新启用。
我该怎么办?
最佳答案
如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();
}
}
关于java - 单击时禁用 JButton 并在 1 秒后重新启用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417747/