Search code examples
javabuttonjavafxcomboboxenter

JavaFX - Bind ButtonAction to ComboBox Item


I'm using an editable ComboBox called testBox with the items testBox.getItems().addAll("A","B","C");. I also have an on Enter-Event

@FXML
public void onEnter(ActionEvent event){
//
}

And ButtonEvents like

@FXML
void aButton(ActionEvent event){
//Do stuff
}
@FXML
void bButton(ActionEvent event){
//Do stuff
}
@FXML
void cButton(ActionEvent event){
//Do stuff
}

How can i fire for example my button 'a'-event when the 'a'-item is selected and Enter pressed?

Please add snippets :).


Solution

  • You could determine the action to be executed in the event handler. E.g. assuming the items list is not modified:

    List<EventHandler<ActionEvent>> handlers = Arrays.asList(
                                                        this::aButton,
                                                        this::bButton,
                                                        this::cButton
        );
    
    @FXML
    public void onEnter(ActionEvent event){
        int index = testBox.getSelectionModel().getSelectedIndex();
        if (index >= 0) {
             handlers.get(index).handle(event);
        }
    }
    

    You could of course also use a item type that contains a property for the handler...