Search code examples
javastringswingjframejtextfield

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...


Solution

  • 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();
         .....
        }
      }
    }