There would be 16 possibilities, if you want to read the checkbox states as binary number with 4 digits.
If you select all 4 CheckBox
es and consider the order of selection, you get 4! = 24
possibilities. Choosing none is another possibility and if you allow an arbitrary number of CheckBox
es to be chosen, your get another 24 for selecting exactly 3 CheckBox
es and another 12 for selecting exactly 2 CheckBox
es and 4 more for selecting exactly 1 CheckBox
summing up to 65 = 24 + 24 + 12 + 4 + 1
.
The simplest solution for saving the order of selection would be by storing the CheckBox
es (or values identifying them) in a List
.
The following example prints the selection interpreted as binary number and also prints the order of selection.
@Override
public void start(Stage primaryStage) throws IllegalAccessException {
VBox container = new VBox();
final List<CheckBox> selectionOrder = new ArrayList<>();
final int checkBoxCount = 4;
for (int i = 0; i < checkBoxCount; i++) {
final CheckBox cb = new CheckBox();
cb.setUserData(i);
cb.selectedProperty().addListener((o, oldValue, newValue) -> {
if (newValue) {
selectionOrder.add(cb);
} else {
selectionOrder.remove(cb);
}
});
container.getChildren().add(cb);
}
Button btn = new Button("print");
btn.setOnAction(evt -> {
System.out.println(selectionOrder.stream().map(c -> c.getUserData().toString()).collect(Collectors.joining(", ", "{ ", " }")));
// print binary
int value = 0;
for (CheckBox cb : selectionOrder) {
value |= (1 << ((Integer) cb.getUserData()));
}
System.out.println(value);
});
container.getChildren().add(btn);
Scene scene = new Scene(container);
primaryStage.setScene(scene);
primaryStage.show();
}
If you don't actually need the order of selection, I'd recommend removing the list, the listener to the selected
property and not set the userData
and instead store the CheckBox
es in a CheckBox[] array
which allows you to do
int value = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].isSelected()) {
value |= (1 << i);
}
}