devhicham
devhicham

Reputation: 567

javafx ComBobox add listener on selected item value

I need to test the value of a selected item to call different methods, so I write this code adding a listener, but the code generate a syntax error

@FXML
private JFXComboBox<String> cmbComp;

cmbComp.valueProperty().addListener(new ChangeListener<String>() {
        public void changed(ObservableValue<String> composant, String oldValue, String newValue) throws SQLException {
            
            if(/*test item value*/){
                /*do something*/
            }else{
                /*do other thing*/
            }
        }
    });

also I don't need an old value and a new one, just test the selected value, how can'I pass arguments ?

Upvotes: 25

Views: 63169

Answers (2)

Ross H
Ross H

Reputation: 36

In case anybody missed it, OP answers in the post:

I found the error, here is the new code, I hope it helps others

cmbComp.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
   System.out.println(newValue);
}); 

Upvotes: 10

rainer
rainer

Reputation: 3411

One solution that is a bit more straightforward and avoids some extra lines of code is adding an action listener (ideally from the scene builder) to the combobox, like this:

private void comboAction(ActionEvent event) {

    System.out.println(comboBox_DbTables.getValue());

}

Upvotes: 18

Related Questions