我需要在點擊時禁用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