使用JavaFX制作正方形的被子

时间:2018-03-07 19:29:11

标签: java user-interface for-loop javafx nested

我一直在尝试使用嵌套for循环使用JavaFX构建Quilt。我一直在尝试这段代码:

def pathToBeRedacted(p: Path, redactProperty: Int): Seq[Vertex] = {

  val seq = Seq.empty[Vertex]
  val l = p.objects()

  val r = createVertexFromPath(l, redactProperty)
  r match {
    case Some(x) => seq :+ x
    case None => seq
  }

}

我不明白......我总是需要在每个循环中声明一个新的Rectangle对象。是否有可能在两个for循环中使用名为“square”的相同矩形。

1 个答案:

答案 0 :(得分:4)

为什么不

for (int x = 0 ; x <= 500 ; x+= 100) {
    for (int y = 0 ; y <= 500 ; y+= 100) {
        Rectangle square = new Rectangle(x, y, 50, 50);
        root.getChildren().add(square);
    }
}

SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Quilt extends Application {

    @Override
    public void start(Stage primaryStage) {
        Pane root = new Pane();
        Paint squareColor = Color.AQUAMARINE ;

        for (int x = 0 ; x <= 500 ; x+=100) {
            for (int y = 0 ; y <= 500 ; y+=100) {
                Rectangle square = new Rectangle(x, y, 50, 50);
                square.setFill(squareColor);
                root.getChildren().add(square);
            }
        }

        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here