0

I'm trying to build "Stick Hero" board game using javafx (JDK8). I use

scene.setOnKeyPressed(e -> {
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (e.getCode().equals(KeyCode.ENTER)) {
                    // do some graphical changes
                    playGame();
                }
            }
        };
        thread.start();
    });

to listen to keyboard and by pressing enter the vertical line turns into a horizontal bridge and the human pass the bridge and this will continue until the length of bridge doesn't match the distance. Now i want to update UI during playGame() method is running. When i tried to do scoreLabel.setText(String.valueOf(score)); and update the scoreLabel text i encountered Not on FX application thread error. playGame() is something like

for (int i = 0; i < cycle; i++) {
        goOneCycle();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        fixPosition();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

and in goOneCycle(); and fixPosition(); i do some graphical changes but it does not shown until the end of the loop. Now i have two questions. First why i can do stuff like scoreLabel.setLayoutX(500); but i cannot do scoreLabel.setText(String.valueOf(score)); i mean in the first case i do not encounter Not on FX application thread. And how i can update scoreLabel text. Notice that i already tried to use Platform.runLater() but when i use this animations and graphical changes will not shown in playGame() method, and just the final frame is shown -all of the animations is done but it does not shown.

szamani20
  • 650
  • 9
  • 26
  • 1
    I think you have a misunderstanding of what threads do and what `Platform.runLater()` does. See if [this question](http://stackoverflow.com/questions/30249493/using-threads-to-make-database-requests/30250308#30250308) helps. For "why can I do stuff like `scoreLabel.setLayout(500)` but not `scoreLabel.setText(...)`, see http://stackoverflow.com/questions/30863205/multi-threading-error-when-binding-a-stringproperty/30868003#30868003 – James_D Jul 01 '15 at 10:49
  • Don't create a new thread on each key press, and wrap `fixPosition` call in `Platform.runLater`. Also you may consider using animation api... – Mohammad Jafar Mashhadi Jul 01 '15 at 15:19

0 Answers0