Leon
Leon

Reputation: 11

Java one code to stop in a loop and not stop the entire program in eclipse

Currently in my brief time with Java I have made a clicker game and I've been trying to implement a way to add a number to an integer (or the int command) every couple of seconds. but whatever I try just stops the entire program completely such as the

Thread.sleep(15000);
wait(15000);

even if they are in a try and catch it just stops the program and not complete a loop every couple of seconds.

Upvotes: 0

Views: 212

Answers (1)

M3579
M3579

Reputation: 910

If you have Thread.sleep(xxx); in the current thread, then yes, it will stop the current thread for xxx seconds. Because (most likely) Thread.sleep is in the same thread that is controlling the GUI, it is pausing your code from executing, freezing your application. There are two ways you can fix this:

Create a new thread and place the timer code in there:

SwingUtilities.invokeLater will add your Runnable to the queue of threads that AWT executes.

    // Because the code is in a different thread, Thread.sleep(1000) will not pause
    // the current thread and the application will continue as normal
    Thread thread = new Thread(new Runnable() {

        int seconds = 0;

        @Override
        public void run()
        {
            while (true) {

                // wait one second
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                };
                // increment seconds
                seconds++;

                System.out.println(seconds);
            }
        }

    });

    thread.start();

Use an existing timer in the Java API

Look at ScheduledThreadPoolExecutor and its scheduleAtFixedRate method. Here's an example. You could also use a swing timer as mentioned in the comment by Hovercraft Full Of Eels.

To use a Swing timer, you import javax.swing.Timer (not java.util.Timer), create a Timer object with the delay and an action listener listening for when it will fire events, and start it.

Timer timer = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent a)
    {
        System.out.println("Timer went off!");
    }
});

// Repeat every second
timer.start();

Note that this code won't execute on its own; you need to have a GUI running.

Upvotes: 2

Related Questions