I am trying to make a GUI with a Start/Stop and an Exit button. Initially the button will have the label "Start". When i push it, its label should become "Stop" and an infinite loop function will begin. I want the loop to run until i press the Stop or Exit button.
The problem is that when the loop starts i can't press neither of the buttons. The "Start" button changes its label into "Stop" only if i make the loop finite and it ends.
Here is the source:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class StartStopButtons extends JFrame{
Component visualComponent = null;
JPanel panel = null;
JLabel statusBar = null;
public StartStopButtons() {
setSize(160, 70);
getContentPane().setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.CENTER);
final JPanel panel_1 = new JPanel();
panel.add(panel_1, BorderLayout.CENTER);
final JButton startButton = new JButton();
startButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("Start")) {
System.out.println("Start Loop");
startButton.setText("Stop");
myLoop ();
}
if (action.equals("Stop")) {
System.out.println("Stop Loop");
System.exit(0);
}
}
});
startButton.setText("Start");
panel_1.add(startButton);
final JButton exitButton = new JButton();
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("Exit")) {
System.exit(0);
}
}
});
panel_1.add(exitButton);
exitButton.setText("Exit");
}
public void myLoop() {
for (int i = 0; ; i++)
System.out.println(i);
}
public static void main(String[] args) {
StartStopButtons ssB = new StartStopButtons();
ssB.setVisible(true);
}
}