Javafx selection events

I have one selector in javafx containing 3 elements that allow AB and C to so change the selection of this element. I want to perform a specific task, so how can I handle these events?

final ChoiceBox cmbx=new ChoiceBox(); try { while(rs.next()) { cmbx.getItems().add(rs.getString(2)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

im adding items to a select from a database ... now i want to know how to handle selectbox events in javafx

+7
source share
2 answers

Add ChangeListener to ChoiceBox selectionmodel and selectedIndexProperty:

 final ChoiceBox<String> box = new ChoiceBox<String>(); box.getItems().add("1"); box.getItems().add("2"); box.getItems().add("3"); box.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) { System.out.println(box.getItems().get((Integer) number2)); } }); 
+15
source

Sebastian explained quite well, although only if you are only interested in the actual value selected in the selection field and don’t really care about the index, you can simply use selectedItemProperty instead of selectedIndexProperty.

Also ChangeListener is a functional interface, you can use lambda here when you go with java 8. I just changed Sebastian's example a little. NewValue is the new value selected.

 ChoiceBox<String> box = new ChoiceBox<String>(); box.getItems().add("1"); box.getItems().add("2"); box.getItems().add("3"); box.getSelectionModel() .selectedItemProperty() .addListener( (ObservableValue<? extends String> observable, String oldValue, String newValue) -> System.out.println(newValue) ); 
+5
source

All Articles