我正在尝试制作一个有 3 个按钮的小程序,所有按钮都是白色的。按下第一个按钮(带有文字“开始!”)将使第二个按钮变为橙色 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");
}
}
Swing 是单线程的。呼唤Thread.sleep
in the EDT
阻止 UI 更新。用一个摇摆计时器 http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)