循环遍历多个ComboBoxes以获取数据JavaFX

时间:2017-10-14 00:19:54

标签: javafx combobox

我正在尝试遍历我创建的所有ComboBox个实例,以获取用户选择的值并将该值添加到新的ArrayList,但我仍然坚持如何继续制作循环获取值。

// row for comboboxes
HBox numBox = new HBox();
numBox.setSpacing(16);
numBox.setAlignment(Pos.CENTER);
vbox.getChildren().add(numBox);

// setup loop to create 8 combo boxes for user to pick
int comboNum = 8;
ComboBox<Integer> binaryBox = new ComboBox<Integer>();
for (int i = 0; i < comboNum; i++) {
    binaryBox = new ComboBox<Integer>();
    List<Integer> binaryList = new ArrayList<Integer>();
    binaryList.add(0);
    binaryList.add(1);

    for (Integer num : binaryList) {
        binaryBox.getItems().addAll(num);
    }

    binaryBox.setValue(0);

    numBox.getChildren().add(binaryBox);
}

// way to get the value from each combo box
ChangeListener<Number> update = 
        (ObservableValue <? extends Number> ov, Number oldValue, Number newValue) -> {
    for (int i = 0; i < comboNum; i++){
        //todo
    }
};

1 个答案:

答案 0 :(得分:3)

每个ComboBox都有SelectionModel,您可以从selectedItem获取{{3}}。首先,创建一个组合框列表,并使用ComboBox<Integer>

的实例填充它
List<ComboBox<Integer>> list = new ArrayList<>();
for (int i = 0; i < comboNum; i++) {
    ComboBox<Integer> binaryBox = new ComboBox<Integer>();
    list.add(binaryBox);
    …
}

稍后,您可以循环浏览列表以使用getSelectedItem()检索所选项目:

for (ComboBox<Integer> combo : list) {
    System.out.println(combo.getSelectionModel().getSelectedItem());
}