2015-04-02 69 views
2

我需要在點擊時禁用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秒鐘,立即禁用和重新啓用的按鈕結束,這不是我想要的,我要做的就是讓按鈕處於禁用狀態並保留兩秒鐘的文本,然後重新啓用。

我該怎麼辦?

+3

不要在UI線程上使用Thread.sleep(UI「凍結」,*沒有機會重新繪製*)。使用計時器。有很多重複。 – user2864740 2015-04-02 16:24:39

+0

您是否嘗試禁用任何在任何事件或計時器代碼之外都有文字的按鈕,以確認它在任何情況下都能產生您想要的效果? – clearlight 2015-04-02 16:24:47

+1

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

回答

5

由於user2864740表示 - 「(凍結不要在UI線程的UI使用的Thread.sleep‘

下面是一個’並沒有有機會重新繪製)使用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(); 
    } 
} 
+0

@Faceplanted閱讀javax.swing.Timer的javadoc。在actionPerformed方法中,disble按鈕,並啓動一個定時器,在1秒後重新啓用它。 – 2015-04-02 16:29:44

+0

關於堆棧交換meta有一個討論,共識是剽竊評論並將其置於答案中。我不是在開玩笑。但是,當然,我會拼湊一個例子。 – clearlight 2015-04-02 16:30:35

+1

@ user2864740感謝您的輸入。我做了一些工作,使答案更加完整。 – clearlight 2015-04-02 16:37:58