Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Start a loop and then carry on?

I'm currently programming in Java. When the user presses the program's start button, I'd like a loop to start. But then I'd like the user to have the ability to stop the loop with a stop button:

public class Program {
    private boolean active;

    // MVC stuff...

    private class StartListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // Do stuff...

            active = true;
            hotelCalifornia();
        }
    }

    private class StopListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // Do stuff...

            active = false;
        }
    }

    public void hotelCalifornia() {
        while (this.active) {
            // The program never leaves!
        }
    }
}

But once the loop is started, the program only performs the actions of the loop. Is there a way around this? Is there a better way to accomplish my goal?

Thanks!

like image 780
Peter Avatar asked Mar 06 '26 17:03

Peter


1 Answers

All the events in a Java Swing application is called in a single Event Thread.

You should create a Swing Timer to call whatever method you want whenever so frequent.

like image 93
Nican Avatar answered Mar 08 '26 07:03

Nican



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!