Reputation: 793
I came across some documents on internet that in javafx you can apply controller to only parent element.
I have a javafx application (built with scenebuilder, eclipse) which has basic structure like this :
SplitPane
{
AnchorPane
{
}
AnchorPane
{
GridPane
{
Pane
{
Label
{
}
}
Pane
{
Label
{
}
}
}
}
}
I want to change the values of those labels at runtime. But it is throwing java.lang.NullPointerException
. My assumption why this is hapening is I'm applying controller to split pane and the labels are not direct children of it so I can't access them.
So questions are : 1) Is my assumption correct ? If not where I'm wrong or missing something ?
2) How to access the labels ?
3) Can I use controller for inner elements (not parent) ?
Thanks in advance, and sorry if the question doesn't make any sense, I'm very very new to javafx.
UPDATE : HERE'S THE CODE i'M USING AND EXCEPTION STACK TRACE :
public class Controller implements Initializable
{
@FXML
private SplitPane splitPane;
@FXML
private AnchorPane anchorPane1;
@FXML
private AnchorPane anchorPane2;
@FXML
private GridPane gridPane;
@FXML
private static Label z1;
@FXML
private static Label z2;
private HashMap<Integer,Label> zoneLabelNames = new HashMap<Integer,Label>();
public Controller()
{
// I have around 20 such labels which's value i'm setting using a loop. For now I've writter two only.
zoneLabelNames.put(0, z1);
zoneLabelNames.put(1, z2);
new Thread(() -> {
while(true)
{
try
{
//some logic to generate new values which will update labels
Platform.runLater(() -> {
//here I'm actually setting values in loop, for now I wrote only two labels.
for(int i =0;i<2;i++)
{
zoneLabelNames.get(i).setText("newly generated value"); // nullPointerException at this line
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
}
Upvotes: 0
Views: 1762
Reputation: 308
To answer your questions:
1) You can access them if you're creating an FXML file. See point 2.
2) If you are wanting to access the Label
s at runtime, you can put an attribute on them in the FXML file you're loading like so: fx:id="_label1"
. Then in your controller class, you are able to create a field for that Label
like so: @FXML private Label _label1;
3) You cannot add a controller to another element other than the root element of the FXML file. If you would like to have a controller on a specific element of the FXML, you have to use an <fx:include source="..."/>
tag. See documentation
I highly recommend that you read through a tutorial on FXML and JavaFX such as the one from Oracle: https://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm
Upvotes: 4