使用javaFX生成随机放置的正方形

时间:2018-02-16 01:54:16

标签: javafx

我试图找出如何使用javaFX生成随机放置的方块。我启动了以下代码,但它无法正常运行。 在调用阶段时,循环似乎只运行一次。我无法绕过如何运行循环,然后调用舞台。

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.shape.*;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;

public class Testing extends Application{
   public void start(Stage primaryStage) {

       for(int i=0; i<=30;i++) {
           float x = (float)(Math.random()*513);
           float y = (float)(Math.random()*513);

           Rectangle r = new Rectangle(x,y,40,40);
           Group root = new Group(r);
           Scene scene = new Scene(root, 512, 512, Color.WHITE);
           primaryStage.setTitle("Assignment 5, a QR Code");
           primaryStage.setScene(scene);
           primaryStage.show();
       }

       //Group root = new Group(r);
       //Scene scene = new Scene(root, 512, 512, Color.WHITE);

       //primaryStage.setTitle("Assignment 5, a QR Code");
       //primaryStage.setScene(scene);
       //primaryStage.show();
   }
   public static void main (String[] args) {
       launch(args);
   }
}

1 个答案:

答案 0 :(得分:2)

就像@James_D说的那样,你在循环中获得了SceneGroupStage。将它们移出更新:另外,就像@James_D指出的那样,List并不是真的需要。只需将Rectangles添加到Group即可。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication42 extends Application {  
    @Override
    public void start(Stage primaryStage) {        
        Group root = new Group();
        for(int i=0; i<=30;i++) 
        {
           float x = (float)(Math.random()*513);
           float y = (float)(Math.random()*513);

           Rectangle r = new Rectangle(x,y,40,40);
           root.getChildren().add(r);//Add each rectangle to the Group.
        }

        Scene scene = new Scene(root, 512, 512, Color.WHITE);
        primaryStage.setTitle("Assignment 5, a QR Code");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }        
}

enter image description here