Java 更改JLabel并等待某个时间退出
我想在单击按钮时更改标签,然后在3秒钟后退出程序。但如果我点击按钮,标签不会改变。3秒钟后它就退出了。这是我的逻辑Java 更改JLabel并等待某个时间退出,java,sleep,Java,Sleep,我想在单击按钮时更改标签,然后在3秒钟后退出程序。但如果我点击按钮,标签不会改变。3秒钟后它就退出了。这是我的逻辑 更改标签 睡3秒钟 然后退出程序 btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Stopping the program."); state.set
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Stopping the program.");
state.setText("Bye...");
state.setBackground(SystemColor.textHighlight);
doStop();
}
});
state = new JLabel("Not listening");
state.setForeground(new Color(255, 255, 255));
state.setBackground(new Color(204, 0, 51));
state.setHorizontalAlignment(SwingConstants.CENTER);
state.setBounds(10, 222, 488, 24);
state.setOpaque(true);
frame.getContentPane().add(state);
public void doStop(){
试一试{
睡眠(3000);
}捕捉(中断异常e){
}
System.exit(0);}
使用doStop()中安装的javax.swing.TImer。像这样
public void doStop() {
Timer t=new Timer(3000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
t.start();
}
我想问题出在线程上。睡眠,试着用定时器代替。 有一个例子:
public void doStop() {
long savedTime=System.currentTimeMillis(), actualTime=System.currentTimeMillis();
while((savedTime+3000 > actualTime) ){
actualTime=System.currentTimeMillis()
}
System.exit(0);}
使用
javax.swing.Timer
如下:
final Timer time= new Timer(3000,new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
删除您的doStop
方法,并将其包含在您的代码中。您按钮的actionListener
如下所示
System.out.println("Stopping the program.");
state.setText("Bye...");
state.setBackground(SystemColor.textHighlight);
time.start();
文件:
以指定的间隔激发一个或多个ActionEvents。示例使用
是使用计时器作为绘图触发器的动画对象
它的框架
学习你的按钮不是叫
btnNewButton\u 1
?所以使用btnNewButton_1.setText(“再见…”)代码>尝试重新绘制();你的frameExceptionstate.setText(“再见…”)代码>内部调用btnNewButton_1.setText(“再见…”)
则这不会更改按钮的文本。此外,从调用将使GUI在线程睡眠时完全无响应。这会给我一个错误,构造函数计时器未定义。
。与以前相同。请确保导入的是javax.swing.timer
是,eclipse导入此import com.sun.speech.freetts.util.Timer代码>。现在,在我将其更改为javax.swing.Timer之后,它就开始工作了。非常感谢。