我正在尝试编写一个简单的GUI,在一个循环中连续显示一些颜色。当用户按下回车键时,循环将停止颜色,并在再次按下回车键时恢复。
我似乎遇到了一些问题。当我按下一次输入时,它继续到阵列中的最后一种颜色是黑色 - 当它应该停在我按下输入的颜色时。当我再次按回车键时,程序似乎只是挂起并且没有响应然后抛出错误,如:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Timer already cancelled.
我使用的是Timer
和TimerTask
吗?
以下是我的课程:
import java.awt.Color;
import java.awt.Container;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
public class Rainbow extends JFrame {
public static final int PAUSED = 0;
public static final int PLAYING = 1;
private Timer timer;
private TimerTask task;
private int state;
private Color[] spectrum;
private Container c;
public static void main(String[] args) {
Rainbow r = new Rainbow();
}
public Rainbow() {
super("TASTE THE RAINBOW!");
createFrame();
setVisible(true);
timer = new Timer();
state = PLAYING;
task = new TimerTask() {
public void run() {
colorChange();
}
};
timer.schedule(task, Calendar.getInstance().getTime(), 1);
}
private void createFrame() {
c = getContentPane();
spectrum = new Color[] {Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.BLACK};
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
c.setFocusable(true);
c.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(state == PLAYING) {
System.out.println(1);
state = PAUSED;
timer.cancel();
} else {
System.out.println(2);
state = PLAYING;
timer.schedule(task, Calendar.getInstance().getTime(), 1);
}
}
}
});
}
private void colorChange() {
try {
while(state == PLAYING) {
for(int i = 0; i < spectrum.length; i++) {
c.setBackground(spectrum[i]);
Thread.sleep(1000);
}
}
} catch(Exception e) {
}
}
}
更新2:
使用Timer类。
添加了字段private Timer timer;
它在构造函数
中初始化timer = new Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorChange();
}
});
timer.start();
colorChange()
删除了while循环。
问题:当你运行程序时,它会在灰色屏幕上停留5秒然后会跳到黑色(最后一种颜色)并保持不变。在执行actionPerformed期间,GUI似乎没有更新?