package ejemplolayouts; import java.awt.event.ActionEvent; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; public class EjemploCardLayout implements ActionListener{ private JFrame f; private JButton b1, b2, b3, b4, b5; public CardLayout cardLayout; public JPanel panelSuperior, panelInferior, panelInf1, panelInf2; public JComboBox combo; public String[] vectorCadena = {"Button 1,2,3", "Button 4,5"}; public EjemploCardLayout() { f = new JFrame("Card Layout"); b1 = new JButton("Button 1"); b2 = new JButton("Button 2"); b3 = new JButton("Button 3"); b4 = new JButton("Button 4"); b5 = new JButton("Button 5"); } public void construyePanelSuperior() { panelSuperior = new JPanel(); combo = new JComboBox(vectorCadena); panelSuperior.setLayout(new FlowLayout()); panelSuperior.add(combo); panelSuperior.getPreferredSize(); } public void construyePanelInferior() { panelInferior = new JPanel(); cardLayout = new CardLayout(); panelInferior.setLayout(cardLayout); /*Al agregar necesitamos 2 argumentos, el objeto a agregar y un nombre referencial */ panelInferior.add(panelInf1, "Button 1,2,3"); panelInferior.add(panelInf2, "Button 4,5"); } public void construyePanelInf1() { panelInf1 = new JPanel(new FlowLayout()); panelInf1.add(b1); panelInf1.add(b2); panelInf1.add(b3); } public void construyePanelInf2() { panelInf2 = new JPanel(new FlowLayout()); panelInf2.add(b4); panelInf2.add(b5); } public void launchFrame() { construyePanelSuperior(); construyePanelInf1(); construyePanelInf2(); construyePanelInferior(); f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS)); f.add(panelSuperior); f.add(panelInferior); f.getPreferredSize(); f.pack(); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.setVisible(true); //creamos el objeto controlador de eventos combo.addActionListener(this); } public static void main(String args[]) { EjemploCardLayout guiWindow2 = new EjemploCardLayout(); guiWindow2.launchFrame(); } public void actionPerformed(ActionEvent evento) { if (evento.getSource() == combo) { if (combo.getSelectedIndex() == 0) { cardLayout.show(panelInferior, "Button 1,2,3"); } if (combo.getSelectedIndex() == 1) { cardLayout.show(panelInferior, "Button 4,5"); } } } }