In this JavaFX source code example, we will see how to create a select and multi-select functionality using ListView in JavaFX.
JavaFX ListView Select Example
Here is a full JavaFX example with a button added which reads the selected items of the ListView when clicked:package sample; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ListView Select Example"); ListView listView = new ListView(); listView.getItems().add("Item 1"); listView.getItems().add("Item 2"); listView.getItems().add("Item 3"); Button button = new Button("Read Selected Value"); button.setOnAction(event -> { ObservableList selectedItems = listView.getSelectionModel().getSelectedItems(); for(Object o : selectedItems){ System.out.println("o = " + o + " (" + o.getClass() + ")"); } }); VBox vBox = new VBox(listView, button); Scene scene = new Scene(vBox, 300, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } }
Output:JavaFX ListView Multi-Select Example
Here is an example of setting the selection mode on the JavaFX ListView:Here is a full JavaFX example that shows how to set a ListView into multiple selection mode, including a button which when clicked will write out the indices of the selected items in the ListView :
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
package sample; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ListView Select Example"); ListView listView = new ListView(); listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listView.getItems().add("Item 1"); listView.getItems().add("Item 2"); listView.getItems().add("Item 3"); Button button = new Button("Read Selected Value"); button.setOnAction(event -> { ObservableList selectedItems = listView.getSelectionModel().getSelectedItems(); for(Object o : selectedItems){ System.out.println("o = " + o + " (" + o.getClass() + ")"); } }); VBox vBox = new VBox(listView, button); Scene scene = new Scene(vBox, 300, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } }
Output:
Comments
Post a Comment