我有一个带有JTextField的类作为实例变量,我在类的构造函数中传递了一个引用。
问题是:如果我尝试使用getText()或setText(),我会不断收到NullPointerException。我费用就像我正确地通过它但我显然做错了什么。任何人都知道我该怎么做才能解决它?
以下代码:
public class GraphicCalculator implements Runnable
{
private JFrame frame;
@Override
public void run()
{
frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
private void createComponents(Container container)
{
GridLayout gl = new GridLayout(3,1);
container.setLayout(gl);
JTextField out = new JTextField();
out.setEnabled(false);
JTextField in = new JTextField("0");
container.add(out);
container.add(in);
container.add(new ButtonPanel(in, out));
}
public JFrame getFrame()
{
return frame;
}
}
问题从这里开始:
public class ButtonPanel extends JPanel
{
private JTextField in;
private JTextField out;
public ButtonPanel(JTextField input, JTextField output)
{
super(new GridLayout(1, 3));
this.createComponents();
this.in = input;
this.out = output;
}
public void createComponents()
{
JButton addition = new JButton("+");
JButton sub = new JButton("-");
JButton zero = new JButton("Z");
System.out.println(this.in.getText());
String s = this.out.getText();
add(addition);
add(sub);
add(zero);
}
}
输出:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ButtonPanel.createComponents(ButtonPanel.java:33)
at ButtonPanel.<init>(ButtonPanel.java:12)
at GraphicCalculator.createComponents(GraphicCalculator.java:32)
at GraphicCalculator.run(GraphicCalculator.java:15)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)