因此,當需要顯示特定卡片(由其名稱標識)時,我需要一種方法來檢查具有該名稱的卡片是否已經存在,以便我可以相應地顯示或創建它。
- 獲取顯示在容器
- 試圖展現出不同的卡
- 獲取組件現在顯示在容器中的電流分量
- 如果這兩個組件都是一樣的,沒有什麼發生了,您需要創建該卡並將其添加到容器中。
這種方法可以節省您自己管理套卡。
編輯:
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();
}
});
}
}
我認爲,姓名(或名稱)是有方法秀()http://download.oracle.com/javase/7/docs/api/java/awt/CardLayout。 html#show%28java.awt.Container,%20java.lang.String%29 from http://download.oracle.com/javase/tutorial/uiswing/layout/card.html – mKorbel 2011-05-18 07:06:15
@mKorbel,我不確定我我懂了。 'show()'方法獲取名稱並顯示與該名稱關聯的卡片。我的問題是如何檢查與特定名稱相關聯的卡是否存在。 – 2011-05-18 07:14:02
@ Shrikant Sharat請在'CAREERS2.2'下面的右側檢查'Related'主題,我在這裏找到f.e. http://stackoverflow.com/questions/2998538/switching-between-cards-in-a-cardlayout-using-getparent – mKorbel 2011-05-18 07:40:58