Search code examples
javajavafxnullpointerexceptiontextfieldfxml

javafx java.lang.NullPointerException controller class


I have my controller class as:

public class Empty_pageController implements Initializable,Runnable{

Which declares all IDs as:

@FXML 
private TextField IDno;
@FXML 
private TextField branch;
...

Now these is my clear() function to clear the FXML form:

public void clear(ActionEvent Event){
    IDno.clear();
    branch.clear();
    bookname.clear();
    ID.clear();
    author.clear();
    address.clear();
    name.clear();
    year.clear();
}

Then I have another class (in same package) that calls these clear():

new Empty_pageController().clear(null);

These gives me following error:

Exception in thread "Thread-4" java.lang.NullPointerException
at library.Empty_pageController.clear(Empty_pageController.java:147)
at library.server.doInBackground(server.java:45)
at library.Empty_pageController.run(Empty_pageController.java:84)
at java.lang.Thread.run(Thread.java:748)

What I tried after seeing some solutions here: I passed the object of contructor class by following code:

s.doInBackground(this);

and then made changes accordingly in the other class's method:

public void doInBackground(Empty_pageController E) throws InterruptedException {

Then I Called using these statement:

E.clear(null);

I got the same error Don't Know where I'm going wrong....?

EDIT:MY FXML file Empty_page.fxml


Solution

  • So when JavaFX initially initializes your Controller Empty_pageController. It will inject

    @FXML 
    private TextField IDno;
    @FXML 
    private TextField branch;
    

    base on that elements fx:id and your FXML tag.

    If you construct that Controller yourself those components aren't being constructed and that's why you're seeing the NullPointerException.

    If you want to clear the components you need to use the instance of your controller that JavaFX created.