Joh*_*ohn 0 java swing event-dispatch-thread thread-sleep
我有一个java swing gui程序,当我点击一个切换按钮时,计时器开始,但我想能够点击相同的按钮,计时器停止,现在它不会让我再次点击它.这是我的计时器课程
public void runningClock(){
isPaused = false;
while(!isPaused){
incrementTime();
System.out.println("Timer Current Time " + getTime());
time.setText(""+ getTime());
try{Thread.sleep(1000);} catch(Exception e){}
}
}
public void pausedClock(){
isPaused=true;
System.out.println("Timer Current Time " + getTime());
time.setText(""+ getTime());
try{Thread.sleep(1000);} catch(Exception e){}
}
Run Code Online (Sandbox Code Playgroud)
这是我的主要课程
private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {
if(btnRun.getText().equals("Run")){
System.out.println("Run Button Clicked");
btnRun.setText("Pause");
test.runningClock();
}
else if(btnRun.getText().equals("Pause")){
System.out.println("Pause Button Clicked");
btnRun.setText("Run");
test.pausedClock();
}
}
Run Code Online (Sandbox Code Playgroud)
你用你的Thread.sleep(...)和while (something)循环冻结了Swing事件线程.解决方案:不要这样做 - 不要在占用事件线程的事件线程上调用代码,并阻止它执行必要的任务.而是改变程序的状态.对于你的时钟,使用Swing Timer.例如,请在这里查看我的答案和代码.