以下代码是我从中获取空指针异常的程序片段。当我按下 GUI 上的“添加”按钮时,一条指向此行的错误消息:
buttonPanel.addButton.setEnabled(false);
被展示。尽管我在 buttonPanel 的构造函数中对其进行了实例化,但我猜测 addButton 出于某种原因为空:
addButton = new JButton("Add");
addButton.addActionListener(buttonListener);
为什么会出现空指针错误
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at AddButtonListener.actionPerformed(AddButtonListener.java:21)
出现?当侦听器在 buttonPanel 类中编码时,程序运行良好,没有错误。在此先感谢您的帮助!
import java.awt.GridLayout;
import javax.swing.*;
public class ButtonPanel extends JPanel{
public JButton addButton,
editButton,
deleteButton,
acceptButton,
cancelButton,
exitButton;
public JPanel topPanel,
exitPanel;
private ParentFrame parentFrame;
public static String buttonStatus;
public ButtonPanel(ParentFrame parent){
parentFrame = parent;
buttonStatus = "idle";
//Create Buttons
AddButtonListener buttonListener = new AddButtonListener(parent);
addButton = new JButton("Add");
addButton.addActionListener(buttonListener);
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
acceptButton = new JButton("Accept");
cancelButton = new JButton("Cancel");
exitButton = new JButton("Exit");
//Manipulate Buttons
acceptButton.setEnabled(false);
cancelButton.setEnabled(false);
//Add to panels
topPanel = new JPanel();
topPanel.add(addButton);
topPanel.add(editButton);
topPanel.add(deleteButton);
topPanel.add(acceptButton);
topPanel.add(cancelButton);
exitPanel = new JPanel();
exitPanel.add(exitButton);
this.setLayout(new GridLayout(2,1));
this.add(topPanel);
this.add(exitPanel);
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddButtonListener implements ActionListener{
private ParentFrame myFrame;
private ButtonPanel buttonPanel;
public AddButtonListener(ParentFrame parent){
myFrame = parent;
buttonPanel = parent.buttonPanel;
}
@Override
public void actionPerformed(ActionEvent ae) {
buttonPanel.buttonStatus = "add";
buttonPanel.addButton.setEnabled(false);
buttonPanel.editButton.setEnabled(false);
buttonPanel.deleteButton.setEnabled(false);
buttonPanel.acceptButton.setEnabled(true);
buttonPanel.cancelButton.setEnabled(true);
}
}
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class ParentFrame extends JFrame{
public ButtonPanel buttonPanel;
public ParentFrame(){
this.setResizable(false);
buttonPanel = new ButtonPanel(this);
this.add(buttonPanel, BorderLayout.SOUTH);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
}
public static void main(String[] args){
ParentFrame frame = new ParentFrame();
frame.setVisible(true);
}
}