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

时间:2017-11-23 22:33:12

标签: java multithreading javafx javafx-8

我想创建一个在每秒传递后递减的计数器,但是当我运行代码时,有时会在TextField中显示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!"出现在Console中。 我有"而(节奏> 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);
  }
}

2 个答案:

答案 0 :(得分:1)

不要阻止 JavaFx应用程序主题使用Thread.Sleep();,因此请使用javafx.concurrent.Taskjavafx.animation.PauseTransition来实现目标

<强>实施例

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

答案 1 :(得分:0)

您可以使用 Platform.runLater 来避免阻止主UI线程

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