'Null Pointer Exception when using getText() function with JTextField [duplicate]

I was working on creating a container class for a JTextField object, but I keep running into trouble whenever I try to get the text in the text field.

class myTextField{
String defaultText;
String currentText = "";
JTextField field;
int xPos;
int yPos;
int xSize;
int ySize;

myTextField(JFrame frame, String newDefaultText, int newXPos, int newYPos, int newXSize, int newYSize){
    defaultText = newDefaultText;
    xPos = newXPos;
    yPos = newYPos;
    xSize = newXSize;
    ySize = newYSize;

    JTextField label = new JTextField(defaultText);
    frame.add(label);
    label.setBounds(xPos, yPos, xSize, ySize);
}

public void setText(String text) {
    this.currentText = field.getText();
    if(text == "") {
        this.currentText = this.defaultText;
    }
    this.currentText = text;
}

public String getText() {
    System.out.println(field.getText());
    this.currentText = field.getText();
    return this.currentText;

    }
}

Whenever I use the getText() function of this class, it gives me this error:

Exception in thread "main" java.lang.NullPointerException
at Examples.myTextField.getText(Example_312.java:182)
at Examples.Example_312.updateFrame(Example_312.java:81)
at Examples.Example_312.main(Example_312.java:49)

Unfortunately, that error isn't very descriptive, and so I'm having trouble finding what's going wrong in my code. I know it's failing when I call "field.getText();", but I don't know why. If someone could explain it to me, or offer a solution, I'd really appreciate it!



Solution 1:[1]

The field JTextField field is never initialized. You must assign a value to this.field before invoking any method on it (you did it for JTextField label, although label is a local variable).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1