java - 单击时禁用 JButton 并在 1 秒后重新启用它?

标签 java swing

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

我该怎么办?

最佳答案

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

关于java - 单击时禁用 JButton 并在 1 秒后重新启用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417747/

相关文章:

Java JCombobox 不更改 JPanel 中的图像

Java Swing : Possible to send robot keyboard input to specific JFrame windows?

java - 理解 GroupLayout 的困难

java - 如何使用测试数据在 java 中创建实例?

java - 在泛型 Java 类中对泛型变量使用数学运算符

java - 销毁 Jframe 对象

java - JButton、带背景图像的 JFrame

java - 使用 swing 布局具有多个自定义组件的 jpanel

java - Spring 执行器可以与非 Web Spring Boot 应用程序一起使用吗?

Java ArrayList : create a copy of array and use seperate from old, 但不创建新对象