如何使用 JButton 停止"while-loop"



学习一些JAVA。我创建了一个简单的SwingUI,一个框架和一个按钮。它应该每2秒返回一次System.out循环。然后按钮将停止循环。但它似乎凝固了转到图

我想在这方面得到一些帮助。如果你能指出我应该读的主题或书名,我这里确实有一些书,大多是"傻瓜"。我将不胜感激。谢谢

/**
* A basic JFrame with a button to stop 'while-loop'
*/
public class TestCode {
private boolean runLoop;
public void initFrameUI() {
// create frame
JFrame frame = new JFrame();
frame.setSize(300, 200);
frame.setVisible(true);
frame.setLayout(null);
// create button
JButton button = new JButton();
frame.add(button);
button.setBounds(60, 60, 90, 30);
button.addActionListener(new ActionListener() {
// button click event
@Override
public void actionPerformed(ActionEvent e) {
runLoop = false;
}
});
}
public void printLoop() {
while (runLoop) {
try {
Thread.sleep(2000);
System.out.println("Loop-da-loop");
} catch (InterruptedException ex) {
Logger.getLogger(TestCode.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) {
// just a start point
new TestCode();
}
public TestCode() {
// constructor for JFrame
initFrameUI();

// start the loop
runLoop = true;
printLoop();
}
}

问题是,您的代码阻塞了主线程。线程本质上负责执行代码,并且可以有多个线程同时运行。主线程是程序启动时执行代码的线程,即执行main(String[])方法的线程。

现在,主线程负责更新UI并对事件做出反应,比如当用户按下按钮时。然而,在您的情况下,主线程被困在方法printLoop()中,并且永远没有机会对按下的按钮做出反应。(它确实检查变量runLoop,但它也负责执行ActionListener,将该变量设置为false。但这种情况在这里从未发生过。(

你可以做的是让一个不同的线程负责重复打印到控制台:

/**
* A basic JFrame with a button to stop 'while-loop'
*/
public class TestCode {
private boolean runLoop;
public void initFrameUI() {
// create frame
JFrame frame = new JFrame();
frame.setSize(300, 200);
frame.setVisible(true);
frame.setLayout(null);
// create button
JButton button = new JButton();
frame.add(button);
button.setBounds(60, 60, 90, 30);
button.addActionListener(new ActionListener() {
// button click event
@Override
public void actionPerformed(ActionEvent e) {
runLoop = false;
}
});
}
public void printLoop() {
while (runLoop) {
try {
Thread.sleep(2000);
System.out.println("Loop-da-loop");
} catch (InterruptedException ex) {
Logger.getLogger(TestCode.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) {
// just a start point
new TestCode();
}
public TestCode() {
// constructor for JFrame
initFrameUI();

// start the loop
runLoop = true;
// Have a different thread call printLoop() so the main thread can handle button presses
new Thread(this::printLoop).start();
}
}

如果您不熟悉使用多个线程,那么在频繁使用它之前应该先了解一下,因为有很多事情可能会出错。

最新更新