Reputation: 21
Here i am here trying to build simple CardLayout but it is throwing NullPointerException at line 19 and line 26. Here is the code. I am trying to show only the firstpanel named panel1 from the given 2 panel which are added indirectly into main controlPanel. I am beginner to Java Swing GUI Programming. PLease help me to solve this problem.
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.CardLayout;
import java.awt.event.*;
import javax.swing.*;
public class test {
private JFrame mainFrame;
private JLabel label1 = new JLabel("This is Label 1");
private JLabel label2 = new JLabel("This is Label 2");
private JPanel controlPanel;
private JPanel panel1;
private JPanel panel2;
public static void main(String[] args){
test coutex = new test();
coutex.prepareGUI();
}
public void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
CardLayout cout = new CardLayout();
controlPanel.setLayout(cout);
panel1.add(label1);
panel2.add(label2);
panel1.setBackground(Color.BLUE);
panel2.setBackground(Color.RED);
controlPanel.add(panel1,"1");
controlPanel.add(panel2,"2");
cout.show(controlPanel,"1");
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
}
Upvotes: 1
Views: 164
Reputation: 8466
Not initialize but trying to assign the following things
private JPanel controlPanel = new jpanel();
private JPanel panel1 = new jpanel();
private JPanel panel2 = new jpanel();
instead of
private JPanel controlPanel;
private JPanel panel1;
private JPanel panel2;
Upvotes: 0
Reputation: 13069
At line 13 , you don't initialize ControlPanel
private JPanel controlPanel;
Upvotes: 0
Reputation: 43872
The issue is here:
controlPanel.setLayout(cout);
The controlPanel
object is never initialized, so you're trying to call a method on a null object. Set it to a new JPanel()
first.
Furthermore, you never initialize panel1
or panel2
. The same advice applies.
Upvotes: 2