While 循环期间主动更新
每次我编写涉及 while 循环的代码时,GUI 都会冻结,从而创建一个无限循环。我想知道如何防止这种情况发生。这是一个示例,我尝试使循环以 Jtogglebutton 的状态为条件,Jtogglebutton 会冻结,从而使循环无限:
boolean state = StartStop.getModel().isSelected(); //whether toggle button is on or off
int speed = SpeedSelection.getValue(); //value of the speed selection bar
ScrollPane.getHorizontalScrollBar().getModel().setValue(position);
while(state == true){
try {
Status.setText("Running...");
StartStop.setText("Stop");
position += speed;
System.out.println(position);
ScrollPane.getHorizontalScrollBar().getModel().setValue(position);
Thread.sleep(250);
state = StartStop.getModel().isSelected();
speed = SpeedSelection.getValue();
//start scrolling the scroll pane
}
catch (InterruptedException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(state == false){
Status.setText("Paused.");
StartStop.setText("Start");
//stop scrolling
}
Everytime I make code involving a while loop, the GUI freezes up, creating an infinite loop. I want to know how I can prevent this. Here is an example, where I try to make the loop conditional on the state of Jtogglebutton, which freezes up, making the loop infinite:
boolean state = StartStop.getModel().isSelected(); //whether toggle button is on or off
int speed = SpeedSelection.getValue(); //value of the speed selection bar
ScrollPane.getHorizontalScrollBar().getModel().setValue(position);
while(state == true){
try {
Status.setText("Running...");
StartStop.setText("Stop");
position += speed;
System.out.println(position);
ScrollPane.getHorizontalScrollBar().getModel().setValue(position);
Thread.sleep(250);
state = StartStop.getModel().isSelected();
speed = SpeedSelection.getValue();
//start scrolling the scroll pane
}
catch (InterruptedException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(state == false){
Status.setText("Paused.");
StartStop.setText("Start");
//stop scrolling
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
UI 事件、重画等由单个线程处理。你导致该线程陷入循环;当它循环时,不会发生任何其他事情(来自 UI 的事件)。您需要在单独的线程中执行您想要执行的操作。
UI events, repainting, etc is handled by a single thread. You're causing that thread to get stuck in a loop; nothing else can happen (events from the UI) while it's looping. You need to do whatever it is you're trying to do in a separate thread.
在 EDT 期间不要使用
Threa#sleep(int)
,这就是为什么你的 GUI 冻结的原因,你有三个选择使用 javax.swing.Timer
使用 SwingWorker
使用 Runnable@Thread
don't use
Threa#sleep(int)
during EDT, that reason why your GUI freeze, you have three choicesuse javax.swing.Timer
use SwingWorker
use Runnable@Thread
Swing 使用单线程。使用另一个线程来执行长时间任务。
通常 SwingWorker 用于这些任务。
Swing uses single thread. Use another thread for long time tasks.
Usually SwingWorker is used for these tasks.