Getting selected element from ListView

廉价感情. 提交于 2020-06-22 09:40:05

问题


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 value of that ListView. What method can I use for that?

I just thought I can also add an event to the onclick and keep it on an attribute for the controller. Is that acceptable too?


回答1:


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);
    }
});



回答2:


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());
        }
 });



回答3:


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



来源:https://stackoverflow.com/questions/13264017/getting-selected-element-from-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!