0

I have a problem with a function I have made for a Whack a mole game in java fx. In the function, I am trying to change the image of 1 to 3 buttons. The problem is that I am trying to set a delay between each image change. I tryed the Wait() function but it gives me a java.lang.IllegalMonitorStateExceptionstrong Exception

The function ChangeImageActive changes the image of a button to tell to the player that he needs to hit the button.

public void ActivateRandomButtons(ArrayList<MSButtons> btnList)
{
    try
    {
        int n;

        int numberOfButtons = rand.nextInt(3);
        for (int i = 0; i < numberOfButtons; i++)
        {
            n = rand.nextInt(9);
            btnList.get(n).ChangeImageActive();
            // Wait 1 second before resuming for loop
            wait(1000);
        }
    }
    catch (java.lang.Exception e)
    {
        System.out.print(e.getMessage().toString());
    }
}

I can show more of my code if needed. Thanks

Farhad
  • 4,119
  • 8
  • 43
  • 66
  • While not the best solution you can use `Thread.sleep(time)`. more info: https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html Note: you should be running the image changing code in a different thread, so that when you use Thread.sleep then it wont lock up you application: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html – sorifiend Oct 02 '17 at 02:23
  • 1
    thats a good idea. I tryed Thread.sleep() but it freezes my application at the very start and then shows the buttons activated with no delay. another thread might be the solution – Philippe Koclas Oct 02 '17 at 02:31
  • For javafx, the Task framework is your friend. – Mordechai Oct 02 '17 at 02:40
  • 2
    Use a `Timeline`. See https://stackoverflow.com/questions/9966136/javafx-periodic-background-task – James_D Oct 02 '17 at 03:25
  • TimeLine worked out great, thanks 1 – Philippe Koclas Oct 03 '17 at 01:21

0 Answers0