Thread sleep in actionPerformed

被刻印的时光 ゝ 提交于 2019-12-11 19:19:52

问题


I am trying to make a tiny program that has 3 buttons, all of them of white color. Pressing the first button (that has the text "Go!") will cause the second button to become orange for 3 seconds and then, after that time, it will become white again AND the third button will become permanently green.

However, in my following code, I have a problem achieving this: When hitting the button "Go!", it causes my program to somewhat freeze for 3 seconds and then the third button becomes green. Can you please help me?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Example extends JFrame
{
public Example(String title)
{
    super(title);
    GridLayout gl = new GridLayout(3,1);
    setLayout(gl);

    final JButton b1 = new JButton("Go!");
    final JButton b2 = new JButton();
    final JButton b3 = new JButton();

    b1.setBackground(Color.WHITE);
    b2.setBackground(Color.WHITE);
    b3.setBackground(Color.WHITE);

    b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            b2.setBackground(Color.ORANGE);
            try
            {
                Thread.sleep(3000);
            } catch (InterruptedException ie) {}
            b2.setBackground(Color.WHITE);
            b3.setBackground(Color.GREEN);
        }
    });                

    add(b1);
    add(b2);
    add(b3);

    setSize(50,200);
    setVisible(true);
}

public static void main(String[] args)
{
    Example ex = new Example("My Example");
}
}

回答1:


Swing is single threaded. Calling Thread.sleep in the EDT prevents UI updates. Use a Swing Timer instead.




回答2:


You're calling Thread.sleep(3000) on the main thread. Hence why your program freezes for three seconds. As @MarounMaroun suggested, you should use a SwingWorker. Here is the documentation.



来源:https://stackoverflow.com/questions/16498174/thread-sleep-in-actionperformed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!