Hi,

I have been trying to create a game loop that is paused when a certain key is pressed. This seemed to work ok in Swing but in javafx the loop locks up the UI, even if i create a seperate thread.

 @FXML
    public void setPaused(KeyEvent e) {

        if (e.getCode().compareTo(KeyCode.P) == 0) {
            //isPaused = !isPaused; Ignored for now
            drawLoop();//begin draw loop
        }

    }

//used to create an interactive loop on the canvas
    public void drawLoop() {

        while(!isPaused){
          redraw();
          try{
          Thread.sleep(17);
          }catch(){
          }
        }

    }

public long redraw() {
        long t = System.currentTimeMillis();
        width = getWidth();
        height = getHeight();
        drawTiles(); //simple draws images onto a canvas, basically a drawImage(buffer) function
        return System.currentTimeMillis() - t;
    }

This is an extremely cutback version of what i have in full ( i had threads at one point for the redraw function, same problem), but ultimately from doing reading iv found that Javafx uses the event dispatcher to handle the UI and apparently calling a loop from a button press locks this thread up...to my understanding i could be wrong.

Can anyone recommend an alternative way to achieve a simple redraw loop that wont freeze my UI in a loop and can be triggered and stop via keyboard? Any help would be appreciated :)

Recommended Answers

All 2 Replies

JavaFX has a rich set of classes to handle animation, so you don't need to mess about with low-level timers or (shudder) timing loops.
Have a look at the javafx.animation.Animation class and its TimeLine subclass, and the AnimationTimer class and related tutorials (this one looks pretty good). It's a higher-level way of dealing with events over time that will need you to do some re-structuring of legacy code, but in the end will save you a lot of tedious coding.

Actually worked a treat and saved me a bunch of unneccessary code. Cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.