Reputation: 3481
I wrote a class that extends JPanel. Here is the code:
public class MedicalMonitorPanel extends JPanel{
public MedicalMonitorPanel() {
super();
initComponents();
}
public void initComponents(){
//layout settings
}
}
Now I want to add my panel to a 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);
}
});
}
}
But I got this exception:
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)
which reports there is something wrong with the add() method. What's wrong?
Upvotes: 1
Views: 2299
Reputation: 9930
Try using SwingUtilities
instead of EventQueue
.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MedicalMonitorDisplay().setVisible(true);
}
});
}
I would also follow Hovercraft Full Of Eels's suggestion of modifying your code to add panel
to the JFrame
in the way he indicates.
EDIT
The problem was caused because of a missing instantiation of the MedicalMonitorPanel
class when using a MedicalMonitorPanel
array.
Upvotes: 2
Reputation: 285430
This makes no sense whatsoever:
add(panel, getContentPane());
Delete this line and start over.
Instead you should add the panel to the contentPane via:
getContentPane().add(panel);
If this still doesn't work, then tell the details -- what goes wrong if you try this?
Also, you can't call revalidate on the contentPane unless you cast it first to JPanel. But you shouldn't need to revalidate the contentPane anyway since you'll call pack()
on the JFrame after adding all components, and that will suffice.
Upvotes: 3