22

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?

Dynelight
  • 2,072
  • 4
  • 25
  • 50
  • There is no control named GridView in JavaFX. – Uluk Biy Nov 07 '12 at 09:24
  • I'm terribly sorry. I meant ListView. Please forgive me. – Dynelight Nov 07 '12 at 11:15
  • I looked into the doc and I found this: "To track selection and focus, it is necessary to become familiar with the SelectionModel and FocusModel classes. A ListView has at most one instance of each of these classes, available from selectionModel and focusModel properties respectively. Whilst it is possible to use this API to set a new selection model, in most circumstances this is not necessary - the default selection and focus models should work in most circumstances." I looked into the FocusModel and there is a getFocusedItem(). Is that what I need? – Dynelight Nov 07 '12 at 12:25

3 Answers3

59

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);
    }
});
Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
1

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

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

BWC semaJ
  • 139
  • 2
  • 16