我需要在点击时禁用JButton,并在2秒后再次启用它,因此我试图从事件处理程序中休眠ui线程,但这会使按钮处于选中状态,您无法读取禁用按钮的文本。在点击后禁用JButton并在1秒后重新启用它?
的代码看起来是这样的:
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秒钟,立即禁用和重新启用的按钮结束,这不是我想要的,我要做的就是让按钮处于禁用状态并保留两秒钟的文本,然后重新启用。
我该怎么办?
不要在UI线程上使用Thread.sleep(UI“冻结”,*没有机会重新绘制*)。使用计时器。有很多重复。 – user2864740 2015-04-02 16:24:39
您是否尝试禁用任何在任何事件或计时器代码之外都有文字的按钮,以确认它在任何情况下都能产生您想要的效果? – clearlight 2015-04-02 16:24:47
http://stackoverflow.com/questions/4348962/thread-sleep-and-repainting,http://stackoverflow.com/questions/18164944/actionlistener-and-thread-sleep,http://stackoverflow.com/questions/14074329/using-sleep-for-a-single-thread,http://stackoverflow.com/questions/21652914/thread-sleep-stopping-my-paint – user2864740 2015-04-02 16:25:34