I have been trying to fiddle around with some layout managers, the CardLayout in particular. The idea I had was : I must be able to accept multiple panels on one frame, i.e, i must have the first panel with a navigation button labeled "Next", and on clicking it, i am expected to see another panel on the frame.
In my sample code, i have three classes: CardLayoutSelf, Page0, Page1.
The design is intended to work as follows :
1. The class CardLayoutSelf contains a variable cards of type JPanel. Also, I have a void createAndShowGUI( ) method. This method is responsible for adding the JPanels representing pages 0 and 1 onto the CardLayout, and in turn, adding it to the JFrame.
2. Pages 0 and 1, represented by the classes Page0 and Page1 each contain navigation buttons, "Next" and "Back" which when clicked shall lead to the corresponding page relative to the present page. Each of these two classes implement ActionListener.
3. I have a method JPanel addComponentToPane() in each of the classes Page0 a Page1, which return the JPanel of that particular page. This method is invoked in createAndShowGUI( ),
The panels are being loaded onto the frame's ContenPane successfully. This is the code for it in class Page0 :
Expand|Select|Wrap|Line Numbers
- public void actionPerformed(ActionEvent e)
- {
- String next = " Next ";
- String back = " Back ";
- CardLayoutSelf c = new CardLayoutSelf();
- CardLayout cl = (CardLayout)(c.cards.getLayout());
- if(next.equalsIgnoreCase(e.getActionCommand()) )
- {
- cl.show(c.cards, "1");
- }
- }
Expand|Select|Wrap|Line Numbers
- void createAndShowGUI()
- {
- cards = new JPanel(new CardLayout());
- JFrame frame = new JFrame(" CardLayouts");
- frame.setLocation(400,300);
- frame.setSize(600,450);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Create and set up the content pane.
- Page0 p0 = new Page0();
- cards.add("0", p0.addComponentToPane());
- Page1 p1 = new Page1();
- cards.add("1", p1.addComponentToPane());
- frame.getContentPane().add (cards,BorderLayout.CENTER);
- //frame.pack();
- frame.setVisible(true);
- }
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Page0.actionPerformed(CardLayoutSelf.java:140)
Can anyone help me out? It seems to be a problem involving actionPerformed( ), but i simply am not able to pin it down.