使用操作侦听器时发生java空指针异常错误
我在img.setIconbg行上得到错误消息null pointer exception;在我的动作监听器的控制器类中,我不知道为什么。我已经对突出显示错误的位置进行了注释。你知道为什么吗使用操作侦听器时发生java空指针异常错误,java,swing,nullpointerexception,actionlistener,Java,Swing,Nullpointerexception,Actionlistener,我在img.setIconbg行上得到错误消息null pointer exception;在我的动作监听器的控制器类中,我不知道为什么。我已经对突出显示错误的位置进行了注释。你知道为什么吗 public class Display { public ImageIcon bg; public JLabel img; public void UI() { Controller listener = new Controller(); bg =
public class Display {
public ImageIcon bg;
public JLabel img;
public void UI() {
Controller listener = new Controller();
bg = new ImageIcon("prophase.png");
img = new JLabel(bg, JLabel.CENTER);
JFrame gameFrame = new JFrame();
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JPanel imgPane = new JPanel();
JPanel panel1 = new JPanel();
imgPane.setLayout(new BorderLayout());
panel1.setLayout(new BorderLayout());
panel1.setOpaque(false);// !!
top.setBorder(BorderFactory.createTitledBorder(""));
bottom.setBorder(BorderFactory.createTitledBorder(""));
JLabel jl = new JLabel("What stage of mitosis is this?", JLabel.CENTER);
imgPane.add(img);// center
top.add(jl);// top center
top.add(listener.wordListener());// top center
bottom.add(listener.answer);// bottom
panel1.add(imgPane, BorderLayout.CENTER);// background image (center)
panel1.add(top, BorderLayout.NORTH);// text field and jlabel (top)
panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used
gameFrame.setJMenuBar(menuBar());
gameFrame.setTitle("Mitosis");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(new ImageIcon("logo.png").getImage());
gameFrame.setResizable(false);
gameFrame.add(panel1);
gameFrame.setSize(400, 300);
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
}
}
另一类:
public class Controller {
Display display = new Display();
private JFrame dialogFrame = new JFrame();
private ImageIcon logo = new ImageIcon("logo.png");
public String word;
public JLabel answer = new JLabel(" ", JLabel.CENTER);
public JTextField wordListener() {
JTextField tf = new JTextField(10);
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {// right click key
JTextField tf = (JTextField) e.getSource();
word = tf.getText();
if (word.equalsIgnoreCase("Prophase")) {
answer.setText("Correct!");
ImageIcon bg = display.bg;
JLabel img = display.img;
bg = new ImageIcon("interphase.png");
img.setIcon(bg);//error
answer.setText(" ");
} else {
answer.setText("Incorrect, try again.");
}
tf.setText("");
}// end actionPerformed method
});
return tf;
}
}
您尚未对名为display的对象调用UI方法
这样做的效果是未为显示对象设置img。当您尝试使用img时,这会出现空指针异常。您可以包括堆栈跟踪吗?为什么使用标记语法错误?如果它是运行时异常,那么它必须已编译,这意味着它不能是语法错误。。。