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

I would like to perform an action when I select an item from mine listviewin javafx 2. I use the Netbeans JavaFX fxml application and SceneBuilder. The method OnMouseClickedin SceneBuilder did not work. This gave me an error that he could not find the method that I had already declared.

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

+5
source share
1 answer

You cannot do this only in an FXML file.
Define the appropriate listView (assuming fx:id="myListView"in FXML) in the Controller class of the FXML file:

@FXML
private ListView<MyDataModel> myListView;

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

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 String.
,

@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);
    }
});
+19

All Articles