Nick
Nick

Reputation: 2641

Java - Not being able to get data from Text Field

I have built this application and I tried to run it but I could not get the data from a JTextField. I don't know what's wrong... Here is the code that is relevant...

Construct the JTextFeild: (File Main.java)

public class Constructor extends javax.swing.JFrame {

   public Constructor() {
      initComponents();
   }

   private void initComponents() {    
      refernce = new javax.swing.JTextField();
      /*Some other code in here*/
   }

   private javax.swing.JTextField refernce;
      /*Some other code in here*/       
   }

Get the data from the Text Field: (File Save.java)

public class Save {

   /*Some other code in here*/

   private javax.swing.JTextField refernce;

   String refernceText = refernce.toString();

}

Error Report:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Save.<init>(Save.java:79)
at Constructor.saveMouseClicked(Constructor.java:444)
at Constructor.access$200(Constructor.java:15)
at Constructor$3.mouseClicked(Constructor.java:210)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
... (it carry on(ask if you need it))

So where have I gone wrong??? Also there are no syntax errors etc...

Upvotes: 1

Views: 654

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94625

Here is an issue,

public class Save {
  private javax.swing.JTextField refernce; <---- ISSUE
  ...
  String refernceText = refernce.toString();  
}

reference field in class Save is initialized with null.

You have to pass the reference of JTextField object reference of Constructor class to Save class.

For instance,

public class Save {
  private javax.swing.JTextField refernce;
  public Save(javax.swing.JTextField refernce){
    this.refernce=refernce;
  } 
  ...
  //and use JTextField in your methods
  void testMethod() {
    if(refernce!=null){
     String refernceText = refernce.getText();
     .....
    }
  }
}

Upvotes: 3

anio
anio

Reputation: 9161

It looks like you declared reference (which by the way is a terrible name for a variable) of type JTextField in the class Save, but you never initialized it. That is why you are getting a NullPointerException.

You new it in the Constructor class.

After you have newed the JTextField in the constructor class, you need to pass the JTextField variable as an argument to either the constructor of the Save class, or to a method of the Save the class, and use that to get the text from the text field.

Also, you don't want to call toString on the JTextField. toString will not get you the data in the textfield. You want getText().

Upvotes: 1

Related Questions