我写了一个扩展 JPanel 的类。这是代码:
public class MedicalMonitorPanel extends JPanel{
public MedicalMonitorPanel() {
super();
initComponents();
}
public void initComponents(){
//layout settings
}
}
现在我想将我的面板添加到 jframe:
public class MedicalMonitorDisplay extends JFrame{
MedicalMonitorPanel panel;
public MedicalMonitorDisplay(){
panel = new MedicalMonitorPanel();
initComponents();
}
private void initComponents(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
getContentPane().add(panel);
getContentPane().validate();
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
new MedicalMonitorDisplay().setVisible(true);
}
});
}
}
但我得到了这个例外:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at MedicalMonitorDisplay.initComponents(MedicalMonitorDisplay.java:53)
at MedicalMonitorDisplay.<init>(MedicalMonitorDisplay.java:40)
at MedicalMonitorDisplay$1.run(MedicalMonitorDisplay.java:63)
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$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
报告 add() 方法有问题。怎么了?