1

我有一个带有 for 循环的对象,它可以在用户指定的次数内切换数组元素的内容。我目前可以在每个循环结束时将更新后的数组输出到 Eclipse 控制台,但我现在必须在 GUI 窗口内显示更新后的数组。我已经有工作代码来显示窗口和带有项目的菜单栏,但我不知道如何让数组在每个循环结束时在网格窗格中显示它的元素。我应该用矩形填充 GridPane(数组的每个元素一个),然后让矩形移动以反映每个循环结束时数组中的变化。我的代码目前如下:

public void start(Stage stagePrimary) throws Exception {
    stagePrimary.setTitle("My Application");
    //Sets the window title.
    Scene scenePrimary = new Scene(new VBox(), 500, 500);
    // Creates the scene.
    // CODE FOR MENU BAR IS HERE        
    KeyFrame KFSim = new KeyFrame(Duration.millis(1000),
    new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent AE1) {
            /* Simulation stuff (i.e. updating the array)
               is supposed to go here. */
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    //Gridpane is supposed to go here.
                }
        });
    }
});

    stagePrimary.setScene(scenePrimary);
    stagePrimary.show();

包含我的数组的类在一个名为 SimInstance 的类中:

public class SimInstance{
    //Irrelevant variables.
    int iNumLoops
    //The number of loops which the simulation should make.
    private char[][] cEditableMap;
    //Array will be updated throughout the simulation.
    public void main(){
        for (int iLoopCount =  0; iLoopCount < iNumLoops; iLoopCount++){
            UpdateMap();
            //Updates the cEditableMap with the new positions.
            PrintMap();
            //Prints the updated map to the Eclipse Console.
        }           
    }
}

我目前没有设置 GridPane 或 Rectangle 对象。

4

1 回答 1

2

如果我正确理解了您的问题:

  1. 您可能不想要一个矩形,而是一个矩形标签。
  2. 如果您的数组是一个简单数组,您可能需要TilePane而不是 GridPane。如果您有一个数组数组,您只需要一个 GridPane。

我会放一些示例代码,但你应该先关注一些在线教程,然后再在这里提问。

TilePane pane = new TilePane();
for (String s : array){
    Label label = new Label(s, new Rectangle(height, width));
    pane.getChildren().add(label);
}

或者:

GridPane pane = new GridPane();
for (int x = 0; x < array.length; x++){
    for (int y = 0; y < array[x].length; y++){
        Label label = new Label(array[x][y], new Rectangle(height, width));
        pane.add(label, x, y);
    }
}
于 2015-01-20T15:55:20.713 回答