我创建了一个创建图像的Java应用程序。我想将代码放在for循环中,放在另一个for循环中,每次代码完成时更新stage / screen并返回第一个for循环,但似乎使用setScene方法和如果我将它们放在第一个for循环中,show方法似乎没有帮助。
对于下面的示例,我希望圆绘图可以自行进行,而不是通过单击。我正在使用thread.sleep方法每隔100毫秒。
package javaFX;
import java.awt.Dimension;
import java.awt.Toolkit;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class circles extends Application {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double WIDTH = screenSize.getWidth() - 80;
double HEIGHT = screenSize.getHeight() - 80;
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, WIDTH, HEIGHT, Color.WHITE);
Canvas canvas = new Canvas(WIDTH, HEIGHT);
root.getChildren().add(canvas);
GraphicsContext graphics = canvas.getGraphicsContext2D();
primaryStage.setTitle("Circles!");
canvas.setOnMouseClicked(clickEvent -> {
for (int i = 0; i < 50; i++) {
double ran = Math.random() * WIDTH;
double nu = Math.random()*1000;
int ranNum = (int) nu;
graphics.strokeOval(ran, ran, ran, ran);
}
});
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
}
答案 0 :(得分:1)
问题解决了!使用AnimationTimer
,如下所示:
import java.awt.Dimension;
import java.awt.Toolkit;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Testing extends Application {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double WIDTH = screenSize.getWidth() - 80;
double HEIGHT = screenSize.getHeight() - 80;
@Override public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, WIDTH, HEIGHT, Color.WHITE);
Canvas canvas = new Canvas(WIDTH, HEIGHT);
root.getChildren().add(canvas);
GraphicsContext graphics = canvas.getGraphicsContext2D();
primaryStage.setTitle("Circles!");
// canvas.setOnMouseClicked(clickEvent -> {
// for (int i = 0; i < 50; i++) {
// double ran = Math.random() * WIDTH;
// graphics.strokeOval(ran, ran, ran, ran);
// }
// });
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
new AnimationTimer() {
@Override public void handle(long currentNanoTime) {
for (int i = 0; i < 50; i++) {
double ran = Math.random() * WIDTH;
graphics.strokeOval(ran, ran, ran, ran);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Do nothing
}
}
}.start();
}
}
JavaFX不会为您更新它。使用类似while循环的问题是,JavaFX并不知道你已经完成了指令(或者至少,这是我从Docs获得的印象)并开始绘制过程。似乎也没有什么东西可以手动强制重绘。所以,你必须使用AnimationTimer。