问题描述
我想创建一个Java FX应用程序,一次在Canvas上绘制线条,在线段之间有明显的时间.在下面的应用程序中,我可以想象绘制一条对角线,停顿一秒钟,然后绘制下一条对角线.而是,FX窗口弹出空白,等待2秒钟,然后同时显示两条对角线.如何达到我想要的效果? javafx.scene.canvas.Canvas
不是要使用的正确对象吗?
I want to create a java FX application that draws lines on a Canvas one step at a time, with a noticable time between line segments. In the below application I have what I imagined would draw a diagonal line, stall a second and then draw the next diagonal line. Instead, the FX window pops up blank, waits 2 seconds, and then shows the two diagonal lines at the same time. How do I achieve the effect I am looking for? Is javafx.scene.canvas.Canvas
not the right object to be using?
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);
/////////////////////////////
}
}
推荐答案
请勿阻止(例如Thread.sleep(...)
)FX应用程序线程.该线程负责渲染场景,因此您将阻止渲染任何更新.
Don't block (e.g. Thread.sleep(...)
) the FX Application Thread. That thread is responsible for rendering the scene, so you will prevent any updates from being rendered.
相反,使用动画来实现以下功能(毕竟,动画实际上就是您在此处创建的内容):
Instead, use an animation for functionality like this (after all, an animation is really what you're creating here):
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();
/////////////////////////////
}
这篇关于Java FX Canvas直到完成才显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!