简体   繁体   English

ComboBox 显示空列表

[英]ComboBox shows empty list

I am trying to use different objects at JavaFX and stacked on combobox.我正在尝试在 JavaFX 中使用不同的对象并堆叠在组合框上。 It shows list without elements.它显示没有元素的列表。

public class Controller extends Application {

public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    primaryStage.setTitle("Hello World");
    primaryStage.setScene(new Scene(root, 300, 275));
    primaryStage.show();

}

public Label label1 = new Label();
public CheckBox cbox1 = new CheckBox();
public ObservableList<String> options = FXCollections.observableArrayList(
         "Option 1",
                "Option 2",
                "Option 3"
        );

public ComboBox comboBox = new ComboBox(options);
......
<ComboBox id="comboBox" fx:id="comboBox" prefWidth="150.0" 
GridPane.columnIndex="1" GridPane.rowIndex="11" />
......

You are not adding the ComboBox from your FXML into your Controller .您没有将FXMLComboBox添加到Controller Instead, you are creating a brand new ComboBox (which is not being displayed in your scene).相反,您正在创建一个全新的ComboBox (不在您的场景中显示)。

You should remove this line:您应该删除此行:

public ComboBox comboBox = new ComboBox(options);

And replace it with this:并将其替换为:

@FXML
private ComboBox comboBox;

Then it's just a matter of setting the items for the combobox:然后只需为组合框设置项目即可:

comboBox.setItems(options);

Why?为什么? The @FXML annotation tells JavaFX that the ComboBox you refer to on the following line has been defined in your FXML file. @FXML注释告诉 JavaFX,您在下一行中引用的ComboBox已在您的FXML文件中定义。 This allows JavaFX to "inject" that object into your controller.这允许 JavaFX 将该对象“注入”到您的控制器中。

Side Note: It is generally not a good idea to use your main class as your controller class (I recommend creating a separate controller class for your FXML).旁注:将主类用作控制器类通常不是一个好主意(我建议为 FXML 创建一个单独的控制器类)。 Your controller class should also include a private void initialize() method (annotated with @FXML ).您的控制器类还应该包含一个private void initialize()方法(用@FXML注释)。 This is where you can setup the parameters for your scene's controls.您可以在此处设置场景控件的参数。 Most introductory JavaFX tutorials will walk you through that process.大多数介绍性 JavaFX 教程将引导您完成该过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM