Ich versuche, zufällige Kreise mit zufälligen x/y Zentren zu zeichnen, aber das Ergebnis meines Codes ist nur ein Kreis in der Mitte der Bühne (Fenster).JavaFX8 - Wie zeichne zufällige Kreise mit zufälligen x/y Zentren?
Ich verwende Task-Klasse, um meine Benutzeroberfläche alle 1 Sekunde zu aktualisieren.
Dies ist mein Code:
package javafxupdateui;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class JavaFXUpdateUI extends Application {
private Stage window;
private StackPane layout;
private Scene scene;
@Override
public void start(Stage primaryStage) {
window = primaryStage;
window.setTitle("JavaFX - Update UI");
layout = new StackPane();
scene = new Scene(layout, 500, 500);
window.setScene(scene);
window.show();
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}
Task task = new Task<Void>() {
@Override
protected Void call() throws Exception {
while (true) {
Platform.runLater(new Runnable() {
@Override
public void run() {
drawCircles();
}
});
Thread.sleep(1000);
}
}
};
public void drawCircles() {
Circle circle;
float x = (float)(Math.random()*501);
float y = (float)(Math.random()*501);
circle = new Circle(x, y, 25, Color.RED);
layout.getChildren().add(circle);
scene.setRoot(layout);
window.setScene(scene);
}
public static void main(String[] args) {
launch(args);
}
}
Das Ergebnis des obigen Codes ist: Result GUI