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?
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With