【发布时间】:2013-05-11 14:33:37
【问题描述】:
我正在尝试制作一个有 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");
}
}
【问题讨论】:
-
Thread.sleep阻止美国东部时间! -
Thread.sleep(...)in actionPerformed:只要说 NO。有关解决方案,请参阅 D 先生的答案。 -
提示:1) 不要设置顶级容器的大小。而是布局内容并致电
pack()。 2) 不要扩展框架或其他顶级容器。而是创建和使用一个实例。
标签: java swing actionlistener event-dispatch-thread thread-sleep