【问题标题】:change size of array with combobox使用组合框更改数组的大小
【发布时间】:2018-05-08 18:16:51
【问题描述】:

我有一个二维按钮数组,设置为生成 6x6 网格。我还有一个组合框,其中包含我希望数组在单击时更改为的不同大小。我该怎么办?

            // Initializing 2D buttons with values i,j
            btn[i][j] = button;
            button.setPrefSize(35, 40);
            gridPane.add(button, i, j);
            button.setDisable(false);
        }
    }

    final ComboBox cb = new ComboBox();
    cb.getItems().addAll(
        "4x4",
        "6x6",
        "8x8",
        "10x10" 
    );

    gridPane.add(cb, 11, 2);

【问题讨论】:

    标签: java arrays javafx combobox


    【解决方案1】:

    您可以将填充gridpane 所需的所有内容放入一个方法中,并在combobox 更改时调用它(我创建init() 只是为了有一个放置代码的地方)。

    ComboBox 上添加listener 并在值更改时获取文本,取2 个ints 并将它们提供给将刷新的方法

    final List<String> values = Arrays.asList("", "X", "O");
    final GridPane gridPane /* = */:
    final ComboBox<String> cb = new ComboBox<>();
    
    public void init() {
        addButtonToGrid(6, 6);
        cb.getItems().addAll("4x4", "6x6", "8x8", "10x10");
        cb.valueProperty().addListener((observable, oldValue, newValue) -> {
            String[] size = newValue.split("x");
            addButtonToGrid(Integer.parseInt(size[0]),Integer.parseInt(size[1]));
        });
    }
    
    private void addButtonToGrid(int sizeR, int sizeC) {
        gridPane.getChildren().clear();
        for (int i = 0; i < sizeC; i++) {
            for (int j = 0; j < sizeR; j++) {
                final Button button = new Button("");
                button.setOnAction(event -> {
                    int valueIndex = values.indexOf(button.getText());
                    button.setText(values.get((valueIndex + 1) % values.size()));
                });
                button.setPrefSize(35, 40);
                gridPane.add(button, i, j);
                button.setDisable(false);
            }
        }
    }
    

    【讨论】:

    • 我已经添加了我的其余代码,你能告诉我这需要去哪里吗?
    • @123abc 我已编辑,如果您需要将所有按钮保留在 List 中,您也可以将其设为属性,在 addButtonToGrid 中清除它并在每次迭代时添加按钮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2011-06-17
    • 2012-03-02
    • 2017-05-20
    相关资源
    最近更新 更多