Issue
I want to make a very simple program in JavaFX. It goes like this:
The user inputs something into a TextField
The program displays the input on a label but on a different Scene
Here is my code:
Controller.java
package sample;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javax.xml.soap.Text;
import java.io.IOException;
public class Controller {
//textField in sample.fxml
@FXML
TextField textField;
//label in display.fxml
@FXML
Label label;
String text;
@FXML
public void enter() throws IOException {
text = textField.getText();
Stage stage = (Stage) (textField).getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource("display.fxml"));
stage.setResizable(false);
stage.setTitle("Display");
stage.setScene(new Scene(root, 300, 275));
label.setText(text);
}
}
Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
There are 2 other FXML files containing either a single textField or a single Label.
But whenever I run this code there is a NullPointerException signaling that label is null, because it hasn't been initialized. How do I fix this?
Solution
I believe you should make antoher controller for the display.fxml file (the other scene). Than in this new controller you can prepare a function to set label value:
DisplayController.java
public class DisplayController {
//label in display.fxml
@FXML
Label label;
public void setLabelText(String s){
label.setText(s);
}
}
and in Controller.java edit enter()
function by calling a new DisplayController.java
instance:
@FXML
public void enter() throws IOException {
text = textField.getText();
Stage stage = (Stage) (textField).getScene().getWindow();
FXMLLoader loader = new FXMLLoader.load(getClass().getResource("display.fxml"));
Parent root = loader.load();
DisplayController dc = loader.getController();
//here call function to set label text
dc.setLabelText(text);
stage.setResizable(false);
stage.setTitle("Display");
stage.setScene(new Scene(root, 300, 275));
}
Answered By - xEdziu
Answer Checked By - Mary Flores (JavaFixing Volunteer)