0

我正在学习 Javafx,并且无法让我的 for 循环在每次迭代时创建一个新矩形。当我运行程序时,它会在左上角创建一个矩形,就是这样。我的目标是根据指定的列数、行数、像素宽和像素高创建一个矩形网格。除了创建矩形之外,一切都经过测试。

for(int i = 0; i < columns; ++i)
    {//Iterate through columns
        for(int j = 0; j < rows; ++j)
        {//Iterate through rows
            Color choice = chooseColor(rectColors);
            //Method that chooses a color

            rect = new Rectangle(horizontal*j, vertical*i, horizontal, vertical);
            //Create a new rectangle(PosY,PosX,width,height)

            rect.setStroke(choice);
            //Give rectangles an outline so I can see rectangles

            root.getChildren().add(rect);
            //Add Rectangle to board

        }
    }

我试图弄清楚为什么没有创建矩形。任何帮助将不胜感激。

4

1 回答 1

0

我使用了与您相同的程序。试试这个并检查你在哪里犯了错误。还要检查您初始化的值。

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

public class RectangleDemo extends Application{

    @Override
    public void start(Stage stage) {
        AnchorPane root = new AnchorPane();
        Scene scene = new Scene(root);
        stage.setScene(scene);

        int columns = 20, rows = 10 , horizontal = 20, vertical = 20;
        Rectangle rect = null;
        for(int i = 0; i < columns; ++i)
        {//Iterate through columns
            for(int j = 0; j < rows; ++j)
            {//Iterate through rows
//              Color choice = chooseColor(rectColors);
                //Method that chooses a color

                rect = new Rectangle(horizontal*j, vertical*i, horizontal, vertical);
                //Create a new rectangle(PosY,PosX,width,height)

                rect.setStroke(Color.RED);
                //Give rectangles an outline so I can see rectangles

                root.getChildren().add(rect);
                //Add Rectangle to board

            }
        }
        scene.setRoot(root);
        stage.show();

    }

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

我希望它会帮助你...

于 2016-02-10T04:52:44.033 回答