Reputation: 47
I have a ComboBox in JavaFX. I want to trigger an event whenever the user types or deletes a character in the ComboBox, so that I can call ComboBox.show() and populate the dropdown with custom text, to make a sort of "predictive text" feature.
However, I cannot find any way to trigger an event upon text change. Does any such methodology exist? If not, can you recommend any other way to accomplish what I am trying to do?
Here's my ComboBox:
ObservableList<String> options =
FXCollections.observableArrayList(
"Option 1",
"Option 2",
"Option 3"
);
ComboBox myComboBox = new ComboBox(options);
myComboBox.setEditable(true);
and here's the code that I've tried to use to trigger an event:
myComboBox.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Event triggered.");
myComboBox.show();
}
});
The problem with this code, however, is that it only goes off when the user presses "Enter" in the ComboBox, or when they select an item from the dropdown.
Any ideas?
Upvotes: 0
Views: 211
Reputation: 209358
You can retrieve the TextField
that is used to edit the content of the combo box with
myComboBox.getEditor();
Like any text input component, the text in it is represented by an observable StringProperty
that you can retrieve with textProperty()
. You can add a listener to this property that is notified if the text changes:
myComboBox.getEditor().textProperty().addListener((obs, oldText, newText) -> {
// do whatever you need with newText (or oldText too if you need)
});
Upvotes: 1