문제

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?

도움이 되었습니까?

해결책

You need to initialize the field before using it.

 txtScreen = new JTextField();

다른 팁

You haven't initialized txtScreen with a value.

you need something like:

txtScreen = new JTextArea();

try posting the code where you initialize it.

There is n existing bug in Java, various releases. In my case I have build 1.6.0_25-b06. The String I pass to JTextPane.setText() is definitely not null, but I get a NPE within setText()--especially on reload. It is html, and tricky, but changing the text slightly prevents the NPE, but leaves an uneasy feeling.

There is a workaround published under the title HTMLEditorKit throws NullPointerException when reloaded. The workaround instantiate a (unused) ParserDelegate{} before the setText() worked for me. http://forums.oracle.com/forums/thread.jspa?threadID=1773568&tstart=0

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top