我正在尝试遍历我创建的所有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
}
};
答案 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());
}