Javafx在循环中创建矩形

Javafx在循环中创建矩形,java,javafx,gridpane,Java,Javafx,Gridpane,我正在学习Javafx,在每次迭代中都很难让for循环创建一个新的矩形。当我运行程序时,它会在左上角创建一个矩形,就是它。我的目标是根据指定的列数、行数、像素宽和像素高创建矩形网格。除了矩形的创建之外,所有的东西都经过了测试 for(int i = 0; i < columns; ++i) {//Iterate through columns for(int j = 0; j < rows; ++j) {//Iterate through ro

我正在学习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

        }
    }
for(int i=0;i

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

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

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);
    }
}
导入javafx.application.application;
导入javafx.scene.scene;
导入javafx.scene.layout.ancorpane;
导入javafx.scene.paint.Color;
导入javafx.scene.shape.Rectangle;
导入javafx.stage.stage;
公共类RectangleDemo扩展了应用程序{
@凌驾
公众假期开始(阶段){
锚烷根=新锚烷();
场景=新场景(根);
舞台场景;
int列=20,行=10,水平=20,垂直=20;
矩形rect=null;
对于(int i=0;i

我希望它能帮助你……

这很有效,但我忘了提到我使用的是GridPane而不是AnchorPane。除此之外,我们的两个代码看起来几乎相同。我想使用GridPane,但无论出于何种原因,它仍然不起作用。如果使用grid pane,则必须提及行索引和列索引。root.add(rect,j,i);使用它而不是root.getChildren().add(rect);您告诉我要使用的代码没有编译,但通过使用GridPane.setConstraints()我让它工作了。非常感谢你!我说的代码也会起作用,伙计。。。您需要删除root.getchildren.add(rect);从代码中,在同一位置添加root.add(rect,j,i);这肯定会奏效的。不客气:)