因此,当需要显示特定卡片(由其名称标识)时,我需要一种方法来检查具有该名称的卡片是否已经存在,以便我可以相应地显示或创建它。
- 获取容器中显示的当前组件
- 尝试显示不同的卡片
- 获取现在显示在容器中的组件
- 如果两个组件相同,则什么都没有发生,您需要创建卡片并将其添加到容器中。
这种方法将节省您自己管理卡片组的时间。
编辑:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutTest implements ActionListener
{
JPanel cards;
public void addComponentToPane(Container pane) {
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { "Red", "Orange", "Green", "Yellow", "Blue"};
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addActionListener(this);
comboBoxPane.add(cb);
cards = new JPanel(new CardLayout());
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
JPanel red = new JPanel();
red.setBackground(Color.RED);
red.setPreferredSize( new Dimension(200, 50) );
cards.add(red, "Red");
JPanel green = new JPanel();
green.setBackground(Color.GREEN);
green.setPreferredSize( new Dimension(200, 50) );
cards.add(green, "Green");
JPanel blue = new JPanel();
blue.setBackground(Color.BLUE);
blue.setPreferredSize( new Dimension(200, 50) );
cards.add(blue, "Blue");
}
public void actionPerformed(ActionEvent e)
{
Component visible = getVisibleCard();
JComboBox comboBox = (JComboBox)e.getSource();
String item = comboBox.getSelectedItem().toString();
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, item);
// change code below to create and show your card.
if (visible == getVisibleCard())
JOptionPane.showMessageDialog(cards, "Card (" + item + ") not found");
}
private Component getVisibleCard()
{
for(Component c: cards.getComponents())
{
if (c.isVisible())
return c;
}
return null;
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("CardLayoutTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CardLayoutTest demo = new CardLayoutTest();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}