问题
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