【问题标题】:Disable a JButton on click and re-enable it 1 second later?单击时禁用 JButton 并在 1 秒后重新启用它?
【发布时间】:2015-04-02 16:22:02
【问题描述】:

我需要在单击时禁用 JButton 并在 2 秒后再次启用它,因此我尝试从事件处理程序中休眠 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 秒内没有文本,并在最后立即禁用和重新启用按钮,这不是我想要的,我的目标是是按钮保持禁用状态并显示文本两秒钟,然后重新启用。

我该怎么办?

【问题讨论】:

标签: java swing


【解决方案1】:

正如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();
    }
}

【讨论】:

  • @Faceplanted 阅读了 javax.swing.Timer 的 javadoc。在 actionPerformed 方法中,禁用按钮,并启动一个计时器,该计时器将在 1 秒后重新启用它。
  • 在堆栈交换元上进行了讨论,共识是抄袭 cmets 并将它们放入答案中。我不是在开玩笑。但可以肯定的是,我会拼凑出一个例子。
  • @user2864740 感谢您的意见。我做了一些工作以使答案更完整。
  • @1sand0s 谢谢,这样更好。我真的很高兴我的评论在一开始就被使用了(不需要链接我!)但我不喜欢太短的答案!一两个参考资料 - JB Nizet 有一个很好的建议 - 将有助于完善细节。
  • @user2864740 我不完全确定他的意思,但如果有人对其进行编辑,我会接受更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多