I noticed a strange behavior when selecting a value from a ComboBox
from the initialize
method annotated with @FXML
. The behavior is that on initial selection from the control's popup sheet, it is not hidden.
Here is an example project
public class Main extends Application {
@Override
public void start(Stage stage) throws Exception {
Button test = new Button("Test");
test.setOnAction(event -> {
TestDialog dialog = new TestDialog(stage);
dialog.show();
});
HBox hBox = new HBox(test);
stage.setScene(new Scene(hBox, 300, 50));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class TestDialog extends Dialog<ButtonType> {
@FXML
private ComboBox<Integer> baudRateComboBox;
public TestDialog(Window owner) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/com/sample/dialogpane.fxml"));
loader.setController(this);
initOwner(owner);
initModality(Modality.APPLICATION_MODAL);
setDialogPane(loader.load());
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@FXML
private void initialize() {
baudRateComboBox.getItems().setAll(4800, 9600, 19200, 38400, 57600, 115200);
baudRateComboBox.getSelectionModel().select((Integer) 115200);
}
}
<DialogPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml">
<content>
<HBox spacing="5" alignment="BASELINE_LEFT">
<Label text="Baudrate:"/>
<ComboBox fx:id="baudRateComboBox"/>
</HBox>
</content>
<buttonTypes>
<ButtonType text="Затвори" buttonData="CANCEL_CLOSE"/>
</buttonTypes>
</DialogPane>
If I select the value asynchronously, the problem disappears.
@FXML
private void initialize() {
baudRateComboBox.getItems().setAll(4800, 9600, 19200, 38400, 57600, 115200);
Platform.runLater(() -> baudRateComboBox.getSelectionModel().select((Integer) 115200));
}
I am using jdk 18.0.1.1 on Ubuntu and javafx 19