使用停止按钮停止无限循环

问题描述 投票:0回答:1

启动无限循环后,我无法关闭JFrame。

我想使用停止按钮停止无限循环。

我正在使用开始按钮启动无限循环。我希望使用停止按钮关闭该循环。

  1. if(stop.getModel()。isPressed()){break;}不起作用
  2. actionListener用于标识按钮单击并使用break语句终止while循环也不起作用 import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class NewClass1 { private String arg = ""; public NewClass1() { JFrame frame = new JFrame("Datacolor software automate"); JButton stop = new JButton("STOP"); stop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { arg = (String)ae.getActionCommand(); System.out.println(arg); } }); JButton button = new JButton("Start"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { int i = 0; while (true) { try { System.out.println(i); i++; if(arg.equals("STOP")) { break; } } catch (Exception e) { System.out.println(e.toString()); } } } }); frame.add(button); frame.add(stop); frame.setLayout(new FlowLayout()); frame.setSize(300,300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new NewClass1(); } }); } }

单击停止按钮时,无限循环必须终止。使用开始按钮启动无限循环后,我无法在JFrame中使用任何按钮。

java swing swingworker
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.