当我运行程序时,我收到此错误nullPointerException:null。
import model.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
public class ButtonPanel extends JPanel implements View
{
private Prison prison;
private LeftInputPanel leftInput;
private DaysPanel days;
private MonthsPanel months;
private YearsPanel years;
private CrimePanel crime;
private AllocateListener aListener;
public ButtonPanel()
{
setup();
build();
}
public void setup()
{
}
public void build()
{
JButton button = new JButton("Allocate Cell");
Dimension size = new Dimension(240, 70);
button.setPreferredSize(size);
button.setMinimumSize(size);
button.setMaximumSize(size);
button.addActionListener(aListener);
add(button);
update();
}
public void update()
{
leftInput.update(); //ERROR ON THIS LINE
}
private class AllocateListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Criminal criminal = new Criminal(leftInput.name());
Period period = new Period(days.days(), months.months(), years.years());
criminal.set(new Crime(crime.getCrime()));
prison.add(criminal);
}
}
}
我的LeftInputPanel - 我从中调用更新方法。
import model.*;
import java.awt.*;
import java.text.*;
import javax.swing.*;
public class LeftInputPanel extends JPanel
{
public JTextField field = new JTextField();
public LeftInputPanel()
{
setup();
build();
}
public void setup()
{
//setLayout(new GridLayout());
Dimension size = new Dimension(100, 190);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
}
public void build()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel(" Name");
field.setPreferredSize(new Dimension(90, 20));
add(label);
add(field);
add(new DaysPanel());
add(new MonthsPanel());
add(new YearsPanel());
}
public String name()
{
return field.getText();
}
public void update()
{
field.setText("");
}
}
错误
java.lang.NullPointerException
at ButtonPanel.update(ButtonPanel.java:43)
at ButtonPanel.build(ButtonPanel.java:38)
at ButtonPanel.<init>(ButtonPanel.java:21)
at RightInputPanel.build(RightInputPanel.java:30)
at RightInputPanel.<init>(RightInputPanel.java:14)
at InputPanel.build(InputPanel.java:24)
at InputPanel.<init>(InputPanel.java:13)
at Panel.build(Panel.java:30)
at Panel.<init>(Panel.java:13)
at Window.build(Window.java:31)
at Window.<init>(Window.java:11)
at Root.main(Root.java:9)
答案 0 :(得分:4)
aListener
尚未初始化(即它仍为null
)并且您尝试将其添加为动作侦听器。我怀疑所需要的只是:
private AllocateListener aListener = new AllocateListener();
答案 1 :(得分:2)
当你遇到异常时,通常会得到一个堆栈跟踪,包括完整的呼叫序列 - 这对于追踪问题是非常宝贵的帮助。
如果您无法从堆栈跟踪中找出问题,则需要将其与相关代码一起提供给我们,并提供行号。
然后我们会更好地通过查找问题来帮助您,更重要的是,向您展示它是如何完成的。