Background Info:
Java FXML instantiates the variable for you. It does not need to explicitly be done again or it will lose the reference that FXML created.
Annotation @FXML are only required on methods to ensure that it is being injected. Although it is good practice to put it above variables, it does not solve the problem
I am trying to change a label's text because I eventually want to display a specific error message for the user to read. At the moment I left the label with the text "label". When I run the program I noticed if i load a new scene and then click the button to change the label it work, but if I try to load the scene "next" and try to change the label's text i get a Null pointer error. So the line that comes right after Main.next() will give me the null pointer, but if i take it out and then click the button "ok" to then change the text of the label it works. The problem is i want it to display the different error messages by changing label and i want to display it as soon as the scene is loaded. Can anyone help me on this?
`<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity"
minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0"
prefWidth="600.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sample.Controller">
<children>
<Label fx:id="lb2" alignment="CENTER" text="Label" />
<Button fx:id="ok" mnemonicParsing="false" onAction="#ok" text="Button" />
</children>
</VBox>`
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="300.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sample.Controller">
<children>
<Button fx:id="pushMe" layoutX="79.0" layoutY="80.0"
mnemonicParsing="false" onAction="#pushMeAction" text="Push me" />
</children>
</Pane>
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import java.awt.*;
import java.io.IOException;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
public class Controller
{
@FXML
public Button pushMe;
public Label lb2;
public void pushMeAction() throws Exception
{
Text text1 = new Text("Hello World");
Main.next();
lb2.setText("Hello");
}
public void ok()
{
lb2.setText("Hello");
}
}
public class Main extends Application {
public static Stage primaryStage;
@Override
public void start(Stage primaryStage) throws Exception{
Parent root =FXMLLoader.load(getClass().getResource("sample.fxml"));
this.primaryStage=primaryStage;
this.primaryStage.setTitle("Hello World");
this.primaryStage.setScene(new Scene(root, 300, 275));
this.primaryStage.show();
}
public static void next() throws IOException
{
Pane menu = FXMLLoader.load(Main.class.getResource("next.fxml"));
Scene myScene = new Scene(menu);
primaryStage.setScene(myScene);
}
public static void main(String[] args) {
launch(args);
}
}