0

我正在尝试制作一个有 3 个按钮的小程序,它们都是白色的。按下第一个按钮(带有文本“Go!”)将导致第二个按钮变为橙色 3 秒钟,然后在此之后再次变为白色,第三个按钮将变为永久绿色。

但是,在我的以下代码中,我遇到了一个问题:当点击按钮“Go!”时,它会导致我的程序有点冻结 3 秒,然后第三个按钮变成绿色。你能帮我么?

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");
}
}
4

2 回答 2

2

Swing 是单线程的。调用阻止 UI 更新Thread.sleepEDT请改用摇摆计时器

于 2013-05-11T14:36:05.917 回答
1

您正在调用Thread.sleep(3000)主线程。因此,为什么您的程序会冻结三秒钟。正如@MarounMaroun 建议的那样,您应该使用SwingWorker. 是文档。

于 2013-05-11T14:36:03.187 回答