我的swing GUI文件存在一些问题,因为我一直收到错误,我使用oracle的教程作为参考,但无论我一直得到同样的错误。
这是错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Calculator.CalcGUI.CalGUI(CalcGUI.java:29)
at Calculator.CalcGUI.access$0(CalcGUI.java:27)
at Calculator.CalcGUI$1.run(CalcGUI.java:74)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
这是我的GUI代码记住,它有点乱,因为我正在尽我所能来解决它。
package Calculator;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class CalcGUI implements ActionListener {
public static boolean geometry = false;
public static boolean is2D = false;
public static boolean is3D = false;
static boolean working = false;
static JFrame cfrm;
static JButton cb1;
static JButton cb2;
static JButton cb3;
static JLabel cl1;
static JLabel cl2;
static JTextField ctf1;
static JTextField ctf2;
static JTextField ctf3;
static ActionListener a, b, c, d, e, f;
private static void CalGUI() {
cfrm.setLayout(new FlowLayout());
cfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cfrm.setSize(300, 600);
cb1 = new JButton();
cb2 = new JButton();
cb3 = new JButton();
do {
if(geometry && is2D != true) {
cfrm.removeAll();
cfrm.add(cb1);
cb1.setText("geometry");
cb1.addActionListener(a);
}
else if(geometry = true && is2D != true) {
cfrm.removeAll();
cfrm.add(cb1);
cfrm.add(cb2);
cb1.setText("2D Shape");
cb2.setText("3D Shape");
cb1.addActionListener(b);
cb2.addActionListener(c);
}
}
while(working = false);
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CalGUI();
}
});
}
}
答案 0 :(得分:3)
cfrm
为空,因此您获得了NullPointerException
。在执行任何set ...方法调用之前实例化如下所示。
cfrm = new JFrame();
cfrm.setLayout(new FlowLayout());
cfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cfrm.setSize(300, 600);
答案 1 :(得分:2)
在开始访问其数据成员或函数之前,您必须实例化cfrm
:
cfrm = new JFrame();
cfrm.setLayout(new FlowLayout());
//...
另外,为什么你的构造函数private
和static
?