1

I have an application using JavaFX.

I have a grid in the main window and a list of steps that a UI element is taking through this grid, I wanted to execute one of these steps every .5 seconds in order to show the route that the element has made around the grid.

I have originally tried implementing it with the following code within a loop:

translateShip(command);

try
{
    Thread.sleep(500);
} catch(InterruptedException e) {
    Thread.currentThread().interrupt();
}

with the translateShip method being as follows:

final String FORWARD_COMMAND = "FORWARD";
final String RIGHT_COMMAND   = "RIGHT";
final String LEFT_COMMAND    = "LEFT";

switch (command)
{
    case FORWARD_COMMAND:
        updateShipPosition ();
        break;

    case RIGHT_COMMAND:
        m_ShipCanvas.setRotate (m_ShipCanvas.getRotate () + 90.0);
        break;

    case LEFT_COMMAND:
        m_ShipCanvas.setRotate (m_ShipCanvas.getRotate () - 90.0);
        break;

    default:
        // Unreachable.
        break;
}

This does not work, the application halts and then moves the ship to the final position at the end. I am assuming because the UI updates are not carried out immediately but added to a queue which never gets reached due to the main thread being halted.

However I'm not sure how to implement this, is there a way to set up a timed callback which could be executed every .5 seconds and add the next UI update?

Or another method?

Any help greatly appreciated!

bd99
  • 57
  • 1
  • 1
  • 8
  • 2
    You never want to sleep on the UI thread. Look into animations: https://docs.oracle.com/javase/8/javafx/visual-effects-tutorial/animations.htm – zmb Dec 05 '15 at 00:34
  • For your purpose you could use the AnimationTimer class. – mipa Dec 05 '15 at 08:27

0 Answers0