I'm having trouble with the CardLayout to have a particular card to be displayed when a button is clicked.
My code is posted below and I am sure that the issue is with the ".show" part but I am not sure what is exactly wrong with it as I am a complete novice with Java and Java Swing so I am pretty much learning as I go!
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CardLayoutTest { public static void main(String[] args) { final String card1Text = "Card 1"; final String card2Text = "Card 2"; final String card3Text = "Card 3"; final JPanel cards; //a panel that uses CardLayout // button commands final String ONE = "ONE"; final String TWO = "TWO"; final String THREE = "THREE"; JFrame frame = new JFrame("CardLayout Test"); //Create the "cards". JPanel card1 = new JPanel(); card1.setBackground(Color.RED); JPanel card2 = new JPanel(); card2.setBackground(Color.GREEN); JPanel card3 = new JPanel(); card3.setBackground(Color.BLUE); //Create the panel that contains the "cards". cards = new JPanel(new CardLayout()); cards.add(card1, card1Text); cards.add(card2, card2Text); cards.add(card3, card3Text); class ControlActionListenter implements ActionListener { public void actionPerformed(ActionEvent e) { CardLayout cl = (CardLayout) (cards.getLayout()); String cmd = e.getActionCommand(); if (cmd.equals(ONE)) { cl.show(cards, ONE); } else if (cmd.equals(TWO)) { cl.show(cards, TWO); } else if (cmd.equals(THREE)) { cl.show(cards, THREE); } } } ControlActionListenter cal = new ControlActionListenter(); JButton btn1 = new JButton("ONE"); btn1.setActionCommand(ONE); btn1.addActionListener(cal); JButton btn2 = new JButton("TWO"); btn2.setActionCommand(TWO); btn2.addActionListener(cal); JButton btn3 = new JButton("THREE"); btn3.setActionCommand(THREE); btn3.addActionListener(cal); JPanel controlButtons = new JPanel(); controlButtons.add(btn1); controlButtons.add(btn2); controlButtons.add(btn3); Container pane = frame.getContentPane(); pane.add(cards, BorderLayout.CENTER); pane.add(controlButtons, BorderLayout.PAGE_END); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); } }