2015-04-02 37 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

相关问题