JavaFX ListView Multiple Selection

后端 未结 1 1469
悲&欢浪女
悲&欢浪女 2021-02-15 11:59

I want to select multiple items from ListView. It would react on mouse click. I tried with this:

selectedLogsList.addAll(logsListView.getSelectionModel().getSele         


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-15 12:09

    If you just want to know which items are selected have a look at my example. Have a look at the setOnMouseClicked() method..

        package application;
    
        import javafx.application.Application;
        import javafx.collections.FXCollections;
        import javafx.collections.ObservableList;
        import javafx.event.Event;
        import javafx.event.EventHandler;
        import javafx.scene.Scene;
        import javafx.scene.control.ListView;
        import javafx.scene.control.SelectionMode;
        import javafx.scene.layout.Pane;
        import javafx.stage.Stage;
    
    
        public class Main extends Application {
            @Override
            public void start(Stage primaryStage) {
                try {
                    Pane  root = new Pane();
                    Scene scene = new Scene(root,600,600);
                    scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
    
                    ListView listView = new ListView();
    
                    ObservableList list = FXCollections.observableArrayList();
    
    
    
    
    
                    listView.setItems(list);
    
                    list.add("item1");
                    list.add("item2");
                    list.add("item3");
    
                    listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    
    
                    listView.setOnMouseClicked(new EventHandler() {
    
                        @Override
                        public void handle(Event event) {
                            ObservableList selectedItems =  listView.getSelectionModel().getSelectedItems();
    
                            for(String s : selectedItems){
                                System.out.println("selected item " + s);
                            }
    
                        }
    
                    });
    
    
                    list.add("item4");  
    
                    root.getChildren().add(listView);
    
                    primaryStage.setScene(scene);
                    primaryStage.show();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
    
            public static void main(String[] args) {
                launch(args);
            }
        }
    

    0 讨论(0)
提交回复
热议问题