import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class CardLayoutTest implements ActionListener,
ListSelectionListener {
JPanel cardPanel;
public void actionPerformed(ActionEvent e) {
String ac = e.getActionCommand();
CardLayout cards = (CardLayout)cardPanel.getLayout();
if(ac.equals("FIRST"))
cards.first(cardPanel);
if(ac.equals("PREVIOUS"))
cards.previous(cardPanel);
if(ac.equals("NEXT"))
cards.next(cardPanel);
if(ac.equals("LAST"))
cards.last(cardPanel);
}
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
String id = (String)((JList)e.getSource()).getSelectedValue();
CardLayout cards = (CardLayout)cardPanel.getLayout();
cards.show(cardPanel, id);
}
}
private JPanel getCardContent() {
CardLayout cards = new CardLayout();
cardPanel = new JPanel(cards);
String[] ids = { "red", "green", "blue", "yellow", "pink" };
Color[] colors = {
Color.red, Color.green, Color.blue, Color.yellow, Color.pink
};
for(int i = 0; i < ids.length; i++) {
cardPanel.add(ids[i], getPanel(ids[i], colors[i]));
}
return cardPanel;
}
private JList getCardList() {
String[] ids = { "red", "green", "blue", "yellow", "pink" };
JList list = new JList(ids);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
return list;
}
private JPanel getPanel(String id, Color color) {
JLabel label = new JLabel(id, JLabel.CENTER);
label.setFont(label.getFont().deriveFont(18f));
JPanel panel = new JPanel(new BorderLayout());
panel.add(label);
panel.setBackground(color);
return panel;
}
private Box getButtonPanel() {
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
String[] ids = { "first", "previous", "next", "last" };
for(int i = 0; i < ids.length; i++) {
JButton button = new JButton(ids[i]);
button.setActionCommand(ids[i].toUpperCase());
button.addActionListener(this);
box.add(button);
box.add(Box.createHorizontalGlue());
}
return box;
}
public static void main(String[] args) {
CardLayoutTest test = new CardLayoutTest();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test.getCardContent());
f.add(test.getCardList(), "Before");
f.add(test.getButtonPanel(), "Last");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}