Issue
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
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
.
Answered By - Fullstack Guy
Answer Checked By - Clifford M. (JavaFixing Volunteer)