Java method run only once the full code after a scheduler runnable shutdown using JavaFX

Im stuck programing a Tetris game trying to learn Java and JavaFX. When I call the method the first time from method start it runs well, when I call it from the thread it only runs partially, and dont add a new node to the pane.

Here is part of the code, you can view it entirely in

@Override
public void start(Stage stage) {
    ...
    stage.show();
    newPieces();
}

public void newPieces() {
    Pieces pieces = new Pieces();
    piece = pieces.createPiece();
    nextPiece = pieces.createPiece();
    boolean add1 = vbox.getChildren().add(nextPiece);
    boolean add2 = pane.getChildren().add(piece);
    translateDown(piece);
}

public void translateDown(Group piece) {
    scheduler.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            boolean translate = piece.getTransforms().add(new Translate(0, 25));
            ...
            ...
            newPieces();
            scheduler.shutdown();
            ...
            ...
       }, 0, 1, TimeUnit.SECONDS);

The method newPieces creates a Group of Rectangles.

Thanks!

Answer

Instead of using a executor to schedule the updates I recommend using a Timeline which executes a frame’s event handler on the application thread. Running the updates on a application thread is important since modifying properies of nodes on a different thread is problematic:

Timeline timeline = new Timeline();

timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(1), evt -> {
    updateBoard(); // do things like moving a piece...

    if (checkLoss()) {
        // stop updates when game is lost
        timeline.stop();
    }
}));

// repeat indefinitely
timeline.setCycleCount(Animation.INDEFINITE);

timeline.play();

You could also use timeline.pause() to pause the game and set the rate property to speed up the game…

Leave a Reply

Your email address will not be published. Required fields are marked *