cojoe
cojoe

Reputation: 45

Loop through multiple ComboBoxes to get data JavaFX

I am trying loop through all the ComboBoxinstances I made in order to get the value the user picks and add that value to a new ArrayList, but I am stuck on how to proceed making the loop to get the values.

// 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
    }
};

Upvotes: 1

Views: 843

Answers (1)

trashgod
trashgod

Reputation: 205775

Each ComboBox has a SelectionModel from which you can obtain the selectedItem. First, create a list of combo boxes and populate it with your instances of ComboBox<Integer>:

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

Later, you can loop through the list to retrieve the selected items using getSelectedItem():

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

Upvotes: 3

Related Questions