Hi, the first time here, but here goes:
I have a JavaFX application that dynamically changes FXML interface shortcuts and the data is retrieved from the Player class.
Two classes considered: Player.javaand InterfaceHandler.java.
The player class stores the player data, and I want to pass the details to the Interface class, which sets the text on the labels.
As a test, my FXML interface has only a button and two labels.
If you click on the button, it calls a method handleButtonthat sets locationLabelto "City".
However, if I call a method locationLabel()in the Player class, I get a NullPointerException when called nameLabel.setText(name). Through debugging, I found that the name string in the Interface class is what should be “Dan”.
Can anyone help?
Main class:
public class Main extends Application {
public void start(final Stage mainStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MainScreen.fxml"));
Scene scene = new Scene(root);
mainStage.setTitle("Main Screen");
mainStage.setScene(scene);
mainStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Player Class:
public class Player{
InterfaceHandler ui = new InterfaceHandler();
public void setNameLabel() {
String name = "Dan";
ui.setName(name);
}
InterfaceHandler Class:
public class InterfaceHandler implements Initializable {
public Label nameLabel;
public Label locationLabel;
public void handleButton(ActionEvent event) throws IOException {
locationLabel.setText("Town");
}
public void setName(String name){
nameLabel.setText(name);
}
}
MainScreen.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" prefHeight="629.0" prefWidth="600.0" snapToPixel="true" style="-fx-background-color: beige;" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.InterfaceHandler">
<children>
<Button fx:id="button1" layoutX="512.0" layoutY="381.0" minWidth="14.0" mnemonicParsing="false" onAction="#handleButton" prefHeight="30.0" prefWidth="51.0" text="Town" visible="true" />
<Label fx:id="nameLabel" layoutX="57.0" layoutY="8.0" prefWidth="216.0" text="blank" />
<Label fx:id="locationLabel" layoutX="68.0" layoutY="27.0" prefWidth="193.0" text="blank" />
</children>
</AnchorPane>