ChoiceBox choiceBox;
choiceBox = new ChoiceBox(model.choiceBoxItems);
choiceBox.getSelectionModel().selectFirst();
choiceBox.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
System.out.println(newValue + " chosen in ChoiceBox");
});
ChoiceBox 정의하기
When clicked, a ChoiceBox control presents a popup containing a list of items from which to choose. In Step 20 of the previous exercise, you clicked the ChoiceBox control shown in Figure 6-9. As a result, a message was printed to the Java console indicating which item you chose. The following code snippet from Listing 6-12 implements this functionality in the StarterApp program:
To initially select the first item in the ChoiceBox, the preceding snippet invokes the selectFirst() method of the choice box’s selectionModel. To detect when the user chooses an item in the ChoiceBox, we add the ChangeListener shown in the snippet to the selectedItem property of the choice box’s selection model. In addition to the code in the preceding snippet, the following snippet from Listing 6-1 contains an instance variable from our StarterAppModel class that contains the objects that will be displayed in the ChoiceBox:
public ObservableList choiceBoxItems = FXCollections.observableArrayList(
"Choice A",
"Choice B",
"Choice C",
"Choice D"
);
Now we move on to a control named MenuButton whose appearance is similar to the ChoiceBox, but whose behavior is similar to a Menu.