I am using a card layout as a refreshing element on a JFrame and want to switch to a specific card after the user selects a button. Is there a way to call a specific card in the CardLayout on an action event?
public class ComboBoxTest() extends JFrame implements ActionListener {
JPanel comboBoxPane = new JPanel(); //use FlowLayout
JButton cb = new JButton("next");
cb.setActionCommand(next);
cb.addActionListener(this);
cb.setText("Forward");
this.add(cb);
comboBoxPane.add(cb);
JButton cb2 = new JButton("next");
cb2.setActionCommand(previous);
cb2.addActionListener(this);
cb2.setText("Back");
this.add(cb2);
comboBoxPane.add(cb2);
//Create the "cards".
card1 = new JPanel();
card1.add(HomeGui.getBody());
card2 = new JPanel();
card2.add(HomeGui.getSecondCard());
card3 = new JPanel();
card3.add(Start.getbody());
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, next);
cards.add(card2, previous);
Container base = getContentPane();
pane.add(header, BorderLayout.BEFORE_FIRST_LINE);
pane.add(comboBoxPane, BorderLayout.AFTER_LAST_LINE);
pane.add(cards);
}
public void actionPerformed(ActionEvent e) {
CardLayout c1 = (CardLayout)(cards.getLayout());
String button = e.getActionCommand();
if(button.equals(next)) {
c1.last(cards);
}
if(button.equals(previous)) {
c1.first(cards);
}
if(button.equals(card3)) {
//calls the third, specified card
}
}
}
You have to use show method of the CardLayout object