Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 395
devhicham Avatar asked Dec 25 '16 19:12

devhicham


People also ask

How do I add options to a ComboBox in Javafx?

We can also create a combo box by using an empty constructor and call its setItems method to set the data. ComboBox comboBox = new ComboBox(options); comboBox. setItems(options); To add more items to the combobox of items with new values.

How to create a combo box in javafx?

You can create a combo box by instantiating the javafx. scene. control. ComboBox class.


2 Answers

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());

}
like image 77
rainer Avatar answered Nov 15 '22 20:11

rainer


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);
}); 
like image 6
Ross H Avatar answered Nov 15 '22 18:11

Ross H