2

I am writing a javaFx application that uses some editable ComboBox controls. I want that when such a ComboBox gains focus, then the text that is there in the ComboBox gets highlighted. So I have this code below:

@FXML
ComboBox box;

box.focusedProperty().addListener(new ChangeListener<Boolean>(){
    @Override
    public void changed(ObservableValue<?extends Boolean> observable, Boolean oldValue, Boolean newValue){
        box.getEditor().selectAll();
    }
});

I even tried the following code:

@FXML
ComboBox box;

box.getEditor().focusedProperty().addListener(new ChangeListener<Boolean>(){
    @Override
    public void changed(ObservableValue<?extends Boolean> observable, Boolean oldValue, Boolean newValue){
        box.getEditor().selectAll();
    }
});

But both are not working. It would be very helpful if somebody could help me out.

Blip
  • 3,061
  • 5
  • 22
  • 50

1 Answers1

2

There is a bug open for this issue: https://bugs.openjdk.java.net/browse/JDK-8129400

You should be able to work around it with the below, which will select the text when you select a new item within the combo box, or whenever you re-focus the combo box

    box.focusedProperty().addListener((observable, oldValue, newValue) -> {
        selectTextIfFocused(box);
    });
    box.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        selectTextIfFocused(box);
    });

Method to select text:

private void selectTextIfFocused(ComboBox box){
    Platform.runLater(() -> {
        if ((box.getEditor().isFocused() || box.isFocused()) && !box.getEditor().getText().isEmpty()) {
            box.getEditor().selectAll();
        }
    });
}
Peter
  • 1,592
  • 13
  • 20