Kyte
Kyte

Reputation: 834

JavaFX Controller class variables not binding to their FXML counterparts

When opening a new javafx window from a running javafx application I cannot bind the fxml variables to a local variable in the controller class.

Please note that for the running application I am able to bind to like-named variables without a problem, populating ComboBoxes in the running application at runtime. Any solutions are welcome.

Code that calls the new class (ServerConfigChooser)

FXMLLoader loader = new FXMLLoader(getClass().getResource("ServerConfigChooser.fxml"));
try{
    Stage stage = new Stage();
    stage.setScene(new Scene( (Parent) loader.load()));
    stage.show();
} catch (IOException ex)...

Example of binding that works in the running application (code executed at runtime)

@FXML
public ComboBox cb_01_fxid;

private void initComboBox(){
    cb_01_fxid.getItems().add(0, "yes");
    cb_01_fxid.getItems().add(0, "no");
}

the fxid "cb_01_fxid" is identical in the controller class to the fxid of the ComboBox object in the .fxml file. This binds without a problem. Below is the code from the controller class for the new window (ServerConfigChooser).

1 @FXML
2 public ComboBox cb_02_fxid;
3
4 public void initComboBoxNewWindow(){
5     cb_02_fxid.addItems(0, "test item 1");
6 }

and the relevant fxml lines from the main application

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="728.9999000000025" prefWidth="735.0000999999975" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="model.Sample">

and the new window

<fx:root type="javafx.scene.layout.AnchorPane" id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="283.0" prefWidth="445.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="model.ServerConfigChooser">
<ComboBox id="cb_02_fxid" layoutX="256.0" layoutY="84.0" onAction="#scc_cb_action">

the program throws a null pointer exception on line 5 (line numbers added for reference). Does anyone know why the second controller isn't binding to the second fxml object? Thanks in advance

Upvotes: 2

Views: 5019

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34498

Your ComboBox fxml part should have fx:id attribute set:

<ComboBox fx:id="cb_02"

This id should have EXACTLY same name as your variable in Controller class.

See tutorial for details: http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm

Upvotes: 4

Related Questions