有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java FX画布在完成之前不会显示

我想创建一个JavaFX应用程序,它一步一步地在画布上绘制线条,线段之间有一个明显的时间间隔。在下面的应用程序中,我会画一条对角线,暂停一秒钟,然后画下一条对角线。相反,FX窗口弹出空白,等待2秒钟,然后同时显示两条对角线。我如何达到我想要的效果?javafx.scene.canvas.Canvas不是要使用的正确对象吗

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

public class FrameCanvas extends Application{
  public static void main(String[] args){
    launch(args);
  }
  @Override
  public void start(Stage primaryStage)throws Exception{
    ////////////////////Basic FX stuff
    Canvas theCanvas = new Canvas(900,900);
    StackPane theLayout = new StackPane();
    theLayout.getChildren().add(theCanvas);
    Scene theScene = new Scene(theLayout,900,900);
    primaryStage.setScene(theScene);
    primaryStage.show();
    ///////////////////////
    /////Drawing an X
    ///////////////////////
    GraphicsContext gc = theCanvas.getGraphicsContext2D();
    Thread.sleep(1000);
    gc.strokeLine(0,0,200,200);
    Thread.sleep(1000);
    gc.strokeLine(200,0,0,200);
    /////////////////////////////
  }
}

共 (1) 个答案

  1. # 1 楼答案

    不要阻止(例如Thread.sleep(...))FX应用程序线程。该线程负责渲染场景,因此您将阻止渲染任何更新

    相反,使用动画实现类似的功能(毕竟,动画就是您在此处创建的):

    public void start(Stage primaryStage)throws Exception{
        ////////////////////Basic FX stuff
        Canvas theCanvas = new Canvas(900,900);
        StackPane theLayout = new StackPane();
        theLayout.getChildren().add(theCanvas);
        Scene theScene = new Scene(theLayout,900,900);
        primaryStage.setScene(theScene);
        primaryStage.show();
        ///////////////////////
        /////Drawing an X
        ///////////////////////
        GraphicsContext gc = theCanvas.getGraphicsContext2D();
    
        Timeline timeline = new Timeline(
            new KeyFrame(Duration.seconds(1), e -> gc.strokeLine(0,0,200,200)),
            new KeyFrame(Duration.seconds(2), e -> gc.strokeLine(200,0,0,200))
        );
        timeline.play();
        /////////////////////////////
    }