Search code examples
javaswingnullpointerexceptionjtextfieldsettext

JTextField.setText() throwing NullPointerException


I'm trying to learn java and I am trying to make a simple calculator. For some reason I am getting a NullPointerException on my TextField.setText().

Here's my code:

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new CalcUI().setVisible(true);
        }
    });

    Calc c = new Calc();
    c.setVals(2,2,'+');
    result = c.doCalc();
    //need to setText(String.valueOf(c.doCalc()))
    txtScreen.setText(""+result);
    System.out.println(result);

}

And in my second class Calc:

    //sets values from calc GUI to local class vars
public void setVals(double n1, double n2, char c){
    NUM1=n1;
    NUM2=n2;
    CHAR=c;
}

//do the math
public double doCalc(){
    switch (CHAR){
        case '+':
            RESULT = NUM1+NUM2;
            break;
    }

    return RESULT;
}

Okay... so I send it values(2,2), it and c.doCalc() returns 4. My System.out.println(result) prints 4 but my txtScreen.setText(""+result); causes a null pointer exception.

Any help?


Solution

  • You need to initialize the field before using it.

     txtScreen = new JTextField();