JavaFX 8 - Creating counter with new Thread have secondary effects

Viewed 514

I want to create a counter that decrements after each second passed, but when i run the code sometimes appears in the TextField the corret value, other times duplicates it, or, the NetBeans Console gives some weird errors.

Can anyone help me with this? I just made several changes in the code but i got no luck with it.

Here is the code:

package javafx_contador;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.control.TextField;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.geometry.Pos;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaFX_Contador extends Application
{
  TextField tf;
  Thread1 contador;

  @Override
  public void start(Stage stage)
  {
    tf = new TextField();
    tf.setEditable(false);
    tf.setMaxWidth(100);
    tf.setAlignment(Pos.CENTER);
    tf.setLayoutX(160);
    tf.setLayoutY(140);
    tf.setFont(Font.font("Cambria", FontWeight.BOLD, 20));

    Pane pane = new Pane();
    pane.setStyle("-fx-background: green;");
    pane.getChildren().add(tf);

    Scene scene = new Scene(pane, 400, 300);

    stage.setResizable(false);
    stage.setTitle("JavaFX (Contador)");
    stage.setScene(scene);
    stage.show();

    pane.requestFocus();

    stage.setOnCloseRequest((WindowEvent we) ->
    {
      System.out.println("A Aplicação vai encerrar.");
      Platform.exit();
      System.exit(0);
    });

    contador = new Thread1();
    contador.start();
  }


  public class Thread1 extends Thread
  {
    int tempo = 60;

    @Override
    public void run()
    {
      tf.setText(Integer.toString(tempo));
      while (tempo > 0)
      {
        try
        {
          Thread1.sleep(1000);
        }
        catch (InterruptedException ex)
        {
          Logger.getLogger(JavaFX_Contador.class.getName()).log(Level.SEVERE, null, ex);
        }
        tempo--;
        tf.setText(Integer.toString(tempo));
      }
      System.out.println("Terminou o tempo!");
    }
  }


  public static void main(String[] args)
  {
    launch(args);
  }
}

I made the code without the "Thread.Sleep" but instead i used "PauseTransition", but there's one problem, the counter stops at -1 even after the message "Terminou o tempo!" appeared in Console. I have "while (tempo > 0)" so i don't understand why it doesn't stop when reaches the value 0.

package javafx_contador;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.control.TextField;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.geometry.Pos;
import javafx.animation.PauseTransition;
import javafx.util.Duration;

public class JavaFX_Contador extends Application
{
  int tempo = 60;
  TextField tf;
  Thread1 contador;

  @Override
  public void start(Stage stage)
  {
    tf = new TextField(Integer.toString(tempo));
    tf.setEditable(false);
    tf.setMaxWidth(100);
    tf.setAlignment(Pos.CENTER);
    tf.setLayoutX(160);
    tf.setLayoutY(140);
    tf.setFont(Font.font("Cambria", FontWeight.BOLD, 20));

    Pane pane = new Pane();
    pane.setStyle("-fx-background: green;");
    pane.getChildren().add(tf);

    Scene scene = new Scene(pane, 400, 300);

    stage.setResizable(false);
    stage.setTitle("JavaFX (Contador)");
    stage.setScene(scene);
    stage.show();

    pane.requestFocus();

    stage.setOnCloseRequest((WindowEvent we) ->
    {
      System.out.println("A Aplicação vai encerrar.");
      Platform.exit();
      System.exit(0);
    });

    contador = new Thread1();
    contador.start();
  }


  public class Thread1 extends Thread
  {
    @Override
    public void run()
    {
      PauseTransition pausa = new PauseTransition(Duration.millis(1000));

      pausa.setOnFinished(e ->
      {
        tempo--;
        tf.setText(Integer.toString(tempo));
      });

      while (tempo > 0)
        pausa.play();

      System.out.println("Terminou o tempo!");
    }
  }


  public static void main(String[] args)
  {
    launch(args);
  }
}
2 Answers

Don't block JavaFx Application thread Using Thread.Sleep();, Therefore use javafx.concurrent.Task or javafx.animation.PauseTransition to achieve your goal

Ex:

    Task task = new Task() {
        @Override
        public Void call() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }
    };

    task.setOnSucceeded((e) -> {
        //
       // YOUR UI CHANGES GOES HERE 
      //
    });
    new Thread(task).start(); 

--------------------OR--------------------

 PauseTransition pause = new PauseTransition(Duration.millis(1000));
    pause.setOnFinished(e -> {
        //
       // YOUR UI CHANGES GOES HERE 
      //
    });
    pause.play();

you can avoid blocking the main UI thread by using Platform.runLater like this

Platform.runLater(new Runnable() {
            @Override
public void run() {
 tf.setText(Integer.toString(tempo));
this.sleep(1000);
}
Related