double_o
double_o

Reputation: 69

Clearing text fields of other class

In my main class I'm having a mask with two textfields, that are defined as the following:

private TextField one;
private TextField two;

In the same class I have button that to clear those fields :

public void newButton() {
    one.clear();
    two.clear();
}

So far, this all works as expected.

I do however have a separat class for my root layout. This class contains a menu bar. I would like to also have the ability to clear my text fields by calling a function from a menu bar item.

I tried:

private void newMenu() {
    Main main = new Main();
    main.newButton();
}

This however is throwing me a java.lang.NullPointerException. Do I miss something here?

Upvotes: 0

Views: 98

Answers (1)

alex.pulver
alex.pulver

Reputation: 2125

If you don't instantiate the one and two TextFields inside the constructor of Main class and instantiate the object inside other method, you will get this error. Check if the objects are null:

public void newButton() {
    if (one != null)
        one.clear();
    if (two != null)
        two.clear();
}

If you don't instantiate the textfields elsewhere, you need to add those lines inside the Main class constructor:

 Main(){
   ...
   one = new TextField();
   two = new TextField();
   ...
}

Upvotes: 1

Related Questions