该组合框控件有一个名为方法setOnAction.此方法接受如文档所述调用的EventHandler:
ComboBox操作,每当更改ComboBox值属性时调用.这可能是由于该值属性被程序改变,当用户在弹出列表或对话框中选择一个项目,或者在可编辑的组合框的情况下,当用户提供他们自己的输入可以是(是经由一个TextField或其他一些输入机制.
当Stage首次加载时,我不希望ComboBox默认为空值,我希望它自动选择ComboBox中的第一个选项(如果有的话).该getSelectionModel() .selectFirst()方法确实更改了ComboBox的选择,但由于某种原因它不会触发EventHandler.但是,调用完全相同方法的按钮的EventHandler 将导致EventHandler触发.我究竟做错了什么?
这是一个使用JDK 8u40显示此行为的简短测试用例:
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
public class Test extends Application {
public void start(Stage stage) throws Exception {
HBox pane = new HBox();
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().add("Hello");
comboBox.getItems().add("World");
comboBox.setOnAction((e) -> {
System.out.println(comboBox.getSelectionModel().getSelectedItem());
});
Button button = new Button("Select First");
button.setOnAction((e) -> {
comboBox.getSelectionModel().selectFirst();
});
comboBox.getSelectionModel().selectFirst();
pane.getChildren().add(comboBox);
pane.getChildren().add(button);
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
}
}
Run Code Online (Sandbox Code Playgroud)
我并不完全理解为什么这是必要的,但是为了让传递给setOBox()方法的EventHandAction()方法触发ComboBox控件,必须首先使用show()方法显示舞台.
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
public class Test extends Application {
public void start(Stage stage) throws Exception {
HBox pane = new HBox();
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().add("Hello");
comboBox.getItems().add("World");
comboBox.setOnAction((e) -> {
System.out.println(comboBox.getSelectionModel().getSelectedItem());
});
Button button = new Button("Select First");
button.setOnAction((e) -> {
comboBox.getSelectionModel().selectFirst();
System.out.println("The button did it!");
});
button.fire();
pane.getChildren().add(comboBox);
pane.getChildren().add(button);
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
comboBox.getSelectionModel().selectFirst();
}
}
Run Code Online (Sandbox Code Playgroud)
对于所有控件而言,这似乎并非完全正确.在上面的示例中,调用按钮上的fire()方法将在显示阶段之前触发EventHandler.