简体   繁体   English

将项目添加到以FXML创建的ComboBox中(在JavaFX应用程序的Controller类内部)

[英]Adding Items to a ComboBox created in FXML (inside the Controller class of a JavaFX Application)

I am using a FXML file to get the GUI part of my application done. 我正在使用FXML文件来完成应用程序的GUI部分。 Inside some H and V-Boxes I got this: 在一些H和V盒中,我得到了:

<ComboBox id="comboBoxLearn" fx:id="comboBoxLearn" prefHeight="51.0" prefWidth="300.0" promptText="Choose List..." style="-fx-font-size: 24;"/>

On the other hand, I got a Controller.java class in which I got this (and some more irrelevant code): 另一方面,我得到了一个Controller.java类,并在其中得到了它(以及一些其他不相关的代码):

@FXML
private ComboBox<String> comboBoxLearn;

/**
 * Initialize
 */
@FXML
public void initialize() {
    comboBoxLearn = new ComboBox<>();
    comboBoxLearn.getItems().setAll("General", "Test", "Test2");
    comboBoxLearn.getSelectionModel().select(0);
}

What I want is: - initializing the comboBoxLearn with the 3 values "General", "Test", "Test2" and set "General" as default value. 我想要的是:-使用3个值“常规”,“测试”,“ Test2”初始化comboBoxLearn,并将“常规”设置为默认值。

It doesn't work right now. 目前无法正常运作。 No exception or error but the box is just blank. 没有异常或错误,但此框只是空白。

EDIT: Leaving out the line 编辑:省去了

comboBoxLearn = new ComboBox<>();

doesn't help either but then an error occurs. 两者均无济于事,但是会发生错误。

It's because you create new Combobox object. 这是因为您创建了新的Combobox对象。 If you annotate Combobox with @FXML you cannot create new object because Java do that basing on your fxml file where you specified your combobox. 如果使用@FXML注释Combobox,则无法创建新对象,因为Java会基于您指定组合框的fxml文件执行此操作。

EDIT 编辑

Ater remove creation of new object there was exception caused by main class because it doesn't apply controller class to view files. 在删除新对象的创建时,主类引起了异常,因为它不将控制器类应用于查看文件。 Controller doesn't have a zero-argument constructor. 控制器没有零参数构造函数。 When fx:controller was added to .fxml file it tries to create instance of that controller which doesn't have zero-argument constructor and program throws exception. 将fx:controller添加到.fxml文件时,它将尝试创建该控制器的实例,该实例没有零参数构造函数,并且程序将引发异常。 Removing fx:controller from fxml file and added below code solved the problem 从fxml文件中删除fx:controller并添加以下代码解决了该问题

FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
loader.setController(new MainController(path));
Pane mainPane = loader.load();

You can initialize your ComboBox and choose a selected value value like this: 您可以初始化ComboBox并选择一个选定的值,如下所示:

<ComboBox id="comboBoxLearn" fx:id="comboBoxLearn">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="General"/>
            <String fx:value="Test"/>
            <String fx:value="Test2"/>
        </FXCollections>
    </items>
    <value>
        <String fx:value="General"/>
    </value>
</ComboBox>

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

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