Java Reference
In-Depth Information
59 cbo.setPrefWidth( 400 );
60 cbo.setValue( "Canada" );
61
62 ObservableList<String> items =
63 FXCollections.observableArrayList(flagTitles);
64 cbo.getItems().addAll(items);
65 pane.setCenter(descriptionPane);
66
67
set combo box value
observable list
add to combo box
// Display the selected country
68
cbo.setOnAction(e -> setDisplay(items.indexOf(cbo.getValue())));
69
70 // Create a scene and place it in the stage
71 Scene scene = new Scene(pane, 450 , 170 );
72 primaryStage.setTitle( "ComboBoxDemo" ); // Set the stage title
73 primaryStage.setScene(scene); // Place the scene in the stage
74 primaryStage.show(); // Display the stage
75 }
76
77 /** Set display information on the description pane */
78 public void setDisplay( int index) {
79 descriptionPane.setTitle(flagTitles[index]);
80 descriptionPane.setImageView(flagImage[index]);
81 descriptionPane.setDescription(flagDescription[index]);
82 }
83 }
The program stores the flag information in three arrays: flagTitles , flagImage , and
flagDescription (lines 13-28). The array flagTitles contains the names of nine coun-
tries, the array flagImage contains image views of the nine countries' flags, and the array
flagDescription contains descriptions of the flags.
The program creates an instance of DescriptionPane (line 31), which was presented
in Listing 16.6, DescriptionPane.java. The program creates a combo box with values from
flagTitles (lines 62-63). The getItems() method returns a list from the combo box (line
64) and the addAll method adds multiple items into the list.
When the user selects an item in the combo box, the action event triggers the execution of
the handler. The handler finds the selected index (line 68) and invokes the setDisplay(int
index) method to set its corresponding flag title, flag image, and flag description on the pane
(lines 78-82).
16.23
How do you create a combo box and add three items to it?
Check
16.24
How do you retrieve an item from a combo box? How do you retrieve a selected item
from a combo box?
Point
16.25
How do you get the number of items in a combo box? How do you retrieve an item at
a specified index in a combo box?
16.26
What events would a ComboBox fire upon selecting a new item?
16.9 ListView
A list view is a control that basically performs the same function as a combo box, but
it enables the user to choose a single value or multiple values.
Key
Point
Figure 16.18 lists several frequently used properties and constructors in ListView . ListView
is defined as a generic class. The generic type T specifies the element type for the elements
stored in a list view.
VideoNote
Use ListView
 
 
 
Search WWH ::




Custom Search