JavaFX8-使用新线程创建计数器具有辅助效果

JavaFX8-使用新线程创建计数器具有辅助效果,java,multithreading,javafx,javafx-8,Java,Multithreading,Javafx,Javafx 8,我想创建一个计数器,它在每过一秒后就递减,但当我运行代码时,有时会在文本字段中显示corret值,有时会重复该值,或者NetBeans控制台会出现一些奇怪的错误 有人能帮我吗? 我只是在代码中做了几处修改,但没有成功 代码如下: package javafx_contador; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import

我想创建一个计数器,它在每过一秒后就递减,但当我运行代码时,有时会在文本字段中显示corret值,有时会重复该值,或者NetBeans控制台会出现一些奇怪的错误

有人能帮我吗? 我只是在代码中做了几处修改,但没有成功

代码如下:

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);
  }
}
我在代码中没有使用“Thread.Sleep”,而是使用了“PauseTransition”,但有一个问题,即使在控制台中出现消息“Terminou o tempo!”之后,计数器仍会在-1处停止。 我有“while(tempo>0)”,所以我不明白它为什么在达到值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);
  }
}

不要使用
thread.Sleep()阻止JavaFx应用程序线程javafx.concurrent.Task
javafx.animation.PauseTransition
来实现您的目标

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(); 
--------------或------------------

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

您可以通过使用平台来避免阻塞主UI线程

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

仅从javafx应用程序线程更新GUI。这可能会有帮助:而且。我尝试了暂停转换,而不是线程。睡眠,但我仍然有一个问题。计数器在达到-1时停止,而在达到0时不停止。我不明白为什么会发生这种情况。我尝试在代码上实现Platform.runLater,但无法运行它!你能告诉我怎么做吗?这如何避免阻塞FX应用程序线程?您在FX应用程序Thread.Platform.runLater上显式调用
Thread.sleep(…)
,就像android的循环器一样,您可以从将其放入事件队列的任何方法调用它,并在调用时执行它。详细信息如下