Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 601
ayu_trance Avatar asked Sep 17 '12 12:09

ayu_trance


1 Answers

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);
    }
});
like image 100
Uluk Biy Avatar answered Oct 19 '22 13:10

Uluk Biy