Dart
Dart

Reputation: 47

TextArea getter from controller class gives NullPointerException

i have a simple javafx FXML app that has a button and a textArea

I am trying to write to the textArea from another class (not the controller)

without sending the textArea to that class ,

i added a getter on my controller class, and on the writingClass i created an object of the ControllerClass

and then trying to write to the textArea , i am getting a java.lang.NullPointerException and java.lang.reflect.InvocationTargetException

what am i doing wrong ???

//Controller.java

package sample;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;

public class Controller {

    @FXML
    Button myButton;

    @FXML
    TextArea myTextArea;
    WriteToTextArea writeToTextArea;

    public TextArea getMyTextArea() {
        return myTextArea;
    }

    public void buttonPressed() {
        writeToTextArea = new WriteToTextArea();
        writeToTextArea.writeThis("trying To Write To TextArea");
    }
}

//WriteToTextArea.java

package sample;
import javafx.scene.control.TextArea;

public class WriteToTextArea {

    private Controller objectController;
    private TextArea textArea;
    public WriteToTextArea() {
        objectController = new Controller();
        textArea = new TextArea();
        textArea = objectController.getMyTextArea();
    }

    public void writeThis(String whatToWrite) {
        textArea.setText(whatToWrite);
    }
}

Upvotes: 0

Views: 328

Answers (1)

James_D
James_D

Reputation: 209674

The textArea is initialized in the controller by the FXMLLoader when the FXML file is loaded. It is only initialized in the controller, and won't be initialized in other instances of the same class (what would it be initialized to?). So when you create a new Controller instance with

 objectController = new Controller();

the textArea in that instance is null, so when you call

textArea.setText(whatToWrite);

you get a null pointer exception.

You need the WriteToTextArea instance to have a reference to the controller itself, not some arbitrary instance of the same class. You can do this by passing a reference to the controller to the WriteToTextArea constructor:

package sample;
import javafx.scene.control.TextArea;

public class WriteToTextArea {

    private Controller objectController;
    private TextArea textArea;

    public WriteToTextArea(Controller objectController) {
        this.objectController = objectController ;
        textArea = objectController.getMyTextArea();
    }

    public void writeThis(String whatToWrite) {
        textArea.setText(whatToWrite);
    }
}

and then in the controller code

public void buttonPressed() {
    writeToTextArea = new WriteToTextArea(this);
    writeToTextArea.writeThis("trying To Write To TextArea");
}

Upvotes: 1

Related Questions