Reputation: 33
I am very new to programming and can't seem to get past this hiccup. I would like to have a choicebox that is populated with options and that is present immediately. I have tried defining the ObservableList and then creating a ComboBox but it is empty when I actually run the code. I do not need to edit this array after it appears. Here is my code:
ObservableList<String> options =
FXCollections.observableArrayList(
"Option 1",
"Option 2",
"Option 3"
);
@FXML
final ComboBox stores = new ComboBox(options);
@FXML
private Label label;
I have created the combobox in the FXML document using Scene Builder with FXid stores.
Any help would be appreciated! Thanks in advance.
Upvotes: 1
Views: 1982
Reputation: 7265
-->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;
Don't try to initialize fxml components,the FXMLLoader
will do this for you.You have first to call the FXMLLoader
so the nodes are initialized and then here are two different solutions based on your implementation:
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);
}
Upvotes: 0
Reputation: 459
when you decorate your javafx component with anotation, you should not initiate it. Only this is ok;
@FXML ComboBox stores;
in the initialize method in your controller class. add this code:
stores.setItems(options);
Upvotes: 1