How to perform an action by selecting an item from ListView in JavaFX 2


Question

I would like to have an action performed when I select an item from my listview in javafx 2. I use a Netbeans JavaFX fxml application and SceneBuilder. The OnMouseClicked method in SceneBuilder did not work. It gave me back an error that it can't find the method that I have already declared.

Can someone tell me how they managed to get it to work?

1
9
10/4/2012 2:10:44 PM

Accepted Answer

You cannot do it in FXML file alone.
Define the corresponding listView (assuming fx:id="myListView" in FXML) in Controller class of the FXML file:

@FXML
private ListView<MyDataModel> myListView;

Add listener in init/start method which will listen to the list view item changes:

myListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<MyDataModel>() {

    @Override
    public void changed(ObservableValue<? extends MyDataModel> observable, MyDataModel oldValue, MyDataModel newValue) {
        // Your action here
        System.out.println("Selected item: " + newValue);
    }
});

MyDataModel can be your own data structure model class or simply a String.
For String example,

@FXML
private ListView<String> myListView;

...
...

ObservableList<String> data = FXCollections.observableArrayList("chocolate", "blue");
myListView.setItems(data);

myListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        // Your action here
        System.out.println("Selected item: " + newValue);
    }
});
28
9/17/2012 1:25:52 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon