Reputation: 4137
I am developing a JavaFX project via Scene Builder. I created quite a long FXML file (I am reporting only a snippet) and the associated controller. Furthermore, I wrote my Application class:
public class Main extends Application {
@Override
public void start(Stage stage) {
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("myfxml.fxml"));
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene scene = new Scene(root);
stage.setTitle("Popolamento dati Ambasciata");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="1150.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.FXController">
...
<children>
<Button id="addobject" mnemonicParsing="false" onAction="#addobject" text="Add Object" GridPane.columnIndex="1" GridPane.halignment="CENTER" GridPane.rowIndex="10" />
<TextField id="objectname" GridPane.columnIndex="1" GridPane.columnSpan="2" GridPane.rowIndex="1" />
Controller:
public class FXController {
@FXML Button addobject;
@FXML TextField objectname;
@FXML
public void addobject() {
objectname.getText();
}
}
}
The application starts correctly and the event handler is invoked, but when accessing the TextField objectname, it is null. Where am I doing wrong?
Upvotes: 3
Views: 1260
Reputation: 45486
You should use fx:id
attribute instead of id
.
If you look at the documentation here:
Assigning an fx:id value to an element creates a variable in the document's namespace that can later be referred to by variable dereference attributes
Note you can still use the id
attribute:
Additionally, if the object's type defines an "id" property, this value will also be passed to the objects setId() method.
So in your case:
<Button fx:id="addobject" ... />
<TextField fx:id="objectname" ... />
Upvotes: 4