我观察到,使用默认按钮时,可编辑的
ComboBox
值不会更新。我的意思是,如果用户在 ComboBox
中输入新值并按 Enter 键,那么他将不会获得他输入的值。如果他使用鼠标单击“确定”按钮,则一切正常。这是我的代码:
public class JavaFxTest7 extends Application {
@Override
public void start(Stage stage) {
var comboBox = new ComboBox<String>();
comboBox.setEditable(true);
var button = new Button("OK");
button.setDefaultButton(true);
button.setOnAction((e) -> {
System.out.println("Value: " + comboBox.valueProperty().get());
});
var vBox = new VBox(comboBox, button);
Scene scene = new Scene(vBox, 400, 400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
如果运行它并在
ComboBox
中输入内容并按 Enter 键,您将看到以下输出:
Value: null
我可以使用此代码修复它:
button.setOnAction((e) -> {
button.requestFocus();//<---- added
System.out.println("Value: " + comboBox.valueProperty().get());
});
但是看起来很奇怪。谁能告诉我如何解决这个问题,或者我可能做错了什么。
看起来默认按钮的操作是由
KEY_PRESSED
事件触发的,但组合框仅提交 KEY_RELEASED
事件的值。由于在释放键之前按下键,因此在提交新值之前会调用按钮的操作处理程序。我想知道这是否会被视为一个错误。
一个快速的解决方法是提前显式提交该值:
comboBox.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.ENTER) {
comboBox.commitValue();
}
});
或者您可以在按钮的操作处理程序中提交值:
button.setOnAction(e -> {
comboBox.commitValue();
System.out.printf("Value: %s%n", comboBox.getValue());
});
这与您当前的解决方案类似,但
commitValue()
的意图比依赖组合框在失去焦点时提交值的事实要清晰得多。