After starting infinite loop, I am unable to close JFrame.
I want to stop infinite loop using stop button.
I am starting an infinite loop using start button. I want close that loop using stop button.
if(stop.getModel().isPressed()){break;} is not working
actionListener used to identify button click and using break statement to terminate while loop is also not working
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(); } }); } }
On clicking stop button infinite loop must terminate. I able not able to use any buttons in JFrame after starting infinite loop using start buttton.