Getting selected element from ListView

前端 未结 3 731
别跟我提以往
别跟我提以往 2021-01-01 17:31

I modify a ListView with the results from a database search in order to use that selection to make another DB request later on.

I want to get the field

相关标签:
3条回答
  • 2021-01-01 17:43

    Say with list view like this:

    ListView<String> listView =new ListView<String>();
    

    Getting selected element from ListView:

    listView.getSelectionModel().getSelectedItem();
    

    Tracking (Listening) the changes in list view selection:

    listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            System.out.println("ListView selection changed from oldValue = " 
                    + oldValue + " to newValue = " + newValue);
        }
    });
    
    0 讨论(0)
  • 2021-01-01 17:44

    You can make a custom event handler, first make a class to handle mouse events.

    import javafx.event.EventHandler;
    import javafx.scene.input.MouseEvent;
    
    class ListViewHandler implements EventHandler<MouseEvent> {
        @Override
        public void handle(MouseEvent event) {
            //this method will be overrided in next step
        }
     }
    

    After making the class, go to where you want the event to happen

     list.setOnMouseClicked(new ListViewHandler(){
            @Override
            public void handle(javafx.scene.input.MouseEvent event) {
                System.out.print(list.getSelectionModel().getSelectedIndex());
            }
     });
    
    0 讨论(0)
  • 2021-01-01 18:02

    JFXtras has a class that extends ListView that has a property called selectedItemProperty which I have found to be handy.

    http://jfxtras.org/overview.html#_listview

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