javafx choicebox events
Asked Answered
C

3

13

i have one choicebox in javafx contains 3 items let A B and C so on change of selection of this item i want to perform certain task so how can i handle this 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 choicebox from database... now i want to know how to handle the events of choicebox in javafx

Canzonet answered 25/1, 2013 at 13:23 Comment(0)
H
23

Add a ChangeListener to the ChoiceBox's 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));
      }
    });
Harr answered 25/1, 2013 at 14:8 Comment(0)
B
13

Sebastian explained well enough though, just incase if you have interest only on actual value selected on the choice box and doesn't much care about index, then you can just use selectedItemProperty instead of selectedIndexProperty.

Also ChangeListener is functional interface, you can use lambda here when you go with java 8. I just little bit modified Sebastian's example. The newValue is newly selected value.

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) );
Bagger answered 9/2, 2016 at 2:5 Comment(3)
This is not working for me on jdk 13.can not resolve method addListener(<lambda expression>)Thanhthank
Yes, it could be no longer valid, since that solution was provided when the JavaFX was included in JDK8. JavaFX is now a standalone project (openjfx.io) and removed from JDK release, so the API may be changed and no longer support lambda expression. Personally I feel sad if lambda is not supported anymoreBagger
It works on my machine, maybe you forgot to import something?Aerosphere
C
7

I know this is an old question, but a simpler way of doing it is using ChoiceBox.setOnAction(EventHandler):

ChoiceBox<String> box = ...;
box.setOnAction(event -> {
    System.out.println(box.getValue());
});

or in FXML:

<ChoiceBox fx:id="id" onAction="#controllerMethod">
Cristobalcristobalite answered 14/1, 2021 at 1:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.