Reputation: 43
I am using a FXML file to get the GUI part of my application done. Inside some H and V-Boxes I got this:
<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):
@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.
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.
Upvotes: 2
Views: 3539
Reputation: 4258
You can initialize your ComboBox
and choose a selected value value like this:
<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>
Upvotes: 1
Reputation: 2007
It's because you create new Combobox object. 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.
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. Removing fx:controller from fxml file and added below code solved the problem
FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
loader.setController(new MainController(path));
Pane mainPane = loader.load();
Upvotes: 0