jtextfield.setText()投掷NullPoInterException
-
13-10-2019 - |
题
我正在尝试学习Java,并且正在尝试制作一个简单的计算器。由于某种原因,我得到了 NullPointerException
在我的 TextField.setText()
.
这是我的代码:
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);
}
在我的第二类计算中:
//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;
}
好吧...所以我发送了 values(2,2)
, ,它 c.doCalc()
返回 4
. 。我的 System.out.println(result)
印刷 4
但是我的 txtScreen.setText(""+result);
导致无效指针异常。
有帮助吗?
解决方案
您需要在使用该字段之前初始化该字段。
txtScreen = new JTextField();
其他提示
您尚未初始化具有值的txtscreen。
您需要类似的东西:
txtScreen = new JTextArea();
尝试将代码发布到初始化的位置。
Java中有n个错误,各种版本。就我而言 build 1.6.0_25-b06
. 。我传递给的字符串 JTextPane.setText()
绝对不是无效的,但我在其中得到了NPE setText()
- 尤其是在重新加载上。它是html且棘手的,但是更改文本会稍微防止NPE,但留下了不安的感觉。
标题下有一个解决方法 HTMLEditorKit throws NullPointerException when reloaded.
解决方法实例化(未使用) ParserDelegate{}
之前 setText()
为我工作。http://forums.oracle.com/forums/thread.jspa?threadid=1773568&tstart=0
不隶属于 StackOverflow