JAVAFX 组合框为空白

JAVAFX ComboBox is blank

我是编程新手,似乎无法克服这个问题。我想要一个填充有选项并且立即出现的选择框。我试过定义 ObservableList 然后创建一个 ComboBox 但是当我实际 运行 代码时它是空的。它出现后我不需要编辑这个数组。这是我的代码:

ObservableList<String> options = 
FXCollections.observableArrayList(
    "Option 1",
    "Option 2",
    "Option 3"
);

@FXML
final ComboBox stores = new ComboBox(options);

@FXML
private Label label;

我使用带有 FXid 存储的 Scene Builder 在 FXML 文档中创建了组合框。

如有任何帮助,我们将不胜感激! 提前致谢。

当您使用注释装饰您的 javafx 组件时,您不应该启动它。只有这个可以;

 @FXML ComboBox stores;

在控制器的初始化方法中 class。 添加此代码:

stores.setItems(options);

-->Your code should be like this:

 ObservableList<String> options = 
    FXCollections.observableArrayList(
        "Option 1",
        "Option 2",
        "Option 3"
    );

    @FXML
    final ComboBox stores ;

    @FXML
    private Label label;

不要尝试初始化 fxml 组件,FXMLLoader 会这样做,因为 you.You 必须先调用 FXMLLoader 以便初始化节点,然后这里有两个不同的节点基于您的实施的解决方案:

Solution 1(Your class implements Initializable(for example))

/**
 * Called after the FXML layout is loaded.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    //Add the ObservableList to the ComboBox
    stores.setItems(options); 

}

Solution 2(Add the method initialize() in your fxml controller,when this method is called then you know that your fxml components have been initialized)

/**
 * Called after the FXML layout is loaded.
 */
 @FXML
 public void initialize(){

    //Add the ObservableList to the ComboBox
    stores.setItems(options); 

 }