Null Pointer Exception when using getText() function with JTextField

Tinkerman255 :

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!

Fullstack Guy :

In your myTextField constructor I assume you wanted to initialize the JTextField field; instance variable but instead you created a local variable JTextField label = new JTextField(defaultText);.

I believe you should change the JTextField label = new JTextField(defaultText); in your constructor to:

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

Then on wards if you invoke the getter getText() you won't face any NullPointerException.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132166&siteId=1