Reputation:
I have a ComboBox (JavaFX) that displays info from a database according to the selected String. For eg: the values in the ComboBox are as follows:
When I have Table 1 selected, and I then select Table 2, the value change is detected and the code is run.
But when I have Table 1 selected, and I re-select Table 1, no value change is detected. Instead I want code to reload Table 1 from the source database.
The current code:
myComboBox.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue ov, String t, String t1) {
myComboBoxValue = t1;
if (t1 != null) {
displayTable(t1)
}
}
});
Upvotes: 1
Views: 489
Reputation: 15
A working approach to react to item selection in ComboBox irrespective if a new item was selected or not can be found here: https://stackoverflow.com/a/25704438/4749209
Basing on this solution, your sample code would stay like this:
myComboBox.showingProperty().addListener((ov, old_show_state, new_show_state) ->
{
// checks if the combobox popup menu was closed
if (new_show_state == false)
{
myComboBoxValue = myComboBox.getValue();
if (myComboBoxValue != null)
{
displayTable(myComboBoxValue)
}
}
});
The only problem to mention is that the reload operation you mentioned will happen if the user clicks outside the combobox popup menu area, as it will close too.
Upvotes: 1
Reputation: 1097
The listener will not be triggered if the old selected value is equal to the new value. However, if this is what you want, you can clear the selected value once the comboBox is clicked.
myComboBox.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue ov, String t, String t1) {
myComboBoxValue = t1;
if (t1 != null) {
displayTable(t1)
}
}
});
myComboBox.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
myComboBox.getSelectionModel().clearSelection();
}
});
Upvotes: 1
Reputation: 18415
You don't change a value when it remains the same, so no event gets fired. Depending on what you are trying to do you could e. g. add a listener to onHidden. It's ugly and doesn't cover e. g. when you set the same value programmatically, but would work for changes via mouse click.
Upvotes: 0