如何在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对象的显示方法

最新更新