您如何在 Java CardLayout 中选择特定卡片?

问题描述

我在 JFrame 上使用卡片布局作为刷新元素,并希望在用户选择按钮后切换到特定卡片。有没有办法在动作事件上调用 cardlayout 中的特定卡片?

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
        }
    }
}

解决方法

必须使用 CardLayout 对象的 show 方法