2016-04-15 144 views
1

我想绘制随机x/y中心的随机圆圈,但我的代码的结果只是在舞台(窗口)中心的一个圆圈。JavaFX8 - 如何绘制随机x/y中心的随机圆?

我使用任务类来更新我的UI每1秒。

这是我的代码:

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

上述代码的结果是: Result GUI

回答

1

到底哪里出问题了

StackPane是布局面板,它由中心的一切默认。由于您想手动将圆圈放置在随机位置,因此您不想使用为您管理布局的窗格。

如何修复

使用PaneGroup代替StackPane。 Pane和Group都不会为您管理项目布局,因此您在特定位置添加的项目将保留在这些位置。

除了

您可能希望使用一个Timeline for your periodic updates而不是runLater任务(虽然后来仍会工作确定,以时间轴你不必应付额外的并行代码的复杂性) 。