Java Reference
In-Depth Information
13
// Declare an array of Strings for flag titles
14
private String[] flagTitles = { "Canada" , "China" , "Denmark" ,
15
"France" , "Germany" , "India" , "Norway" , "United Kingdom" ,
16
"United States of America" };
17
18
// Declare an ImageView array for the national flags of 9 countries
19
private ImageView[] ImageViews = {
20
new ImageView( "image/ca.gif" ),
21
new ImageView( "image/china.gif" ),
22
new ImageView( "image/denmark.gif" ),
23
new ImageView( "image/fr.gif" ),
24
new ImageView( "image/germany.gif" ),
25
new ImageView( "image/india.gif" ),
26
new ImageView( "image/norway.gif" ),
27
new ImageView( "image/uk.gif" ),
28
new ImageView( "image/us.gif" )
29 };
30
31 @Override // Override the start method in the Application class
32 public void start(Stage primaryStage) {
33 ListView<String> lv = new ListView<>
34 (FXCollections.observableArrayList(flagTitles));
35 lv.setPrefSize( 400 , 400 );
36
create a list view
set list view properties
lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
37
38 // Create a pane to hold image views
39 FlowPane imagePane = new FlowPane( 10 , 10 );
40 BorderPane pane = new BorderPane();
41 pane.setLeft( new ScrollPane(lv));
42 pane.setCenter(imagePane);
43
44
place list view in pane
lv.getSelectionModel().selectedItemProperty().addListener(
listen to item selected
45
ov -> {
46
imagePane.getChildren().clear();
47
for (Integer i: lv.getSelectionModel().getSelectedIndices()) {
48
imagePane.getChildren().add(ImageViews[i]);
add image views of selected
items
49
}
50
});
51
52 // Create a scene and place it in the stage
53 Scene scene = new Scene(pane, 450 , 170 );
54 primaryStage.setTitle( "ListViewDemo" ); // Set the stage title
55 primaryStage.setScene(scene); // Place the scene in the stage
56 primaryStage.show(); // Display the stage
57 }
58 }
The program creates an array of strings for countries (lines 14-16) and an array of nine
image views for displaying flag images for nine countries (lines 19-29) in the same order
as in the array of countries. The items in the list view are from the array of countries
(lineĀ 34). Thus, the index 0 of the image view array corresponds to the first country in
the list view.
The list view is placed in a scroll pane (line 41) so that it can be scrolled when the number
of items in the list extends beyond the viewing area.
By default, the selection mode of the list view is single. The selection mode for the list
view is set to multiple (line 36), which allows the user to select multiple items in the list
view. When the user selects countries in the list view, the listener's handler (lines 44-50) is
executed, which gets the indices of the selected items and adds their corresponding image
views to the flow pane.
 
 
Search WWH ::




Custom Search