【问题标题】:Swing CardLayout摇摆卡布局
【发布时间】:2012-05-30 04:23:09
【问题描述】:

当您添加两张具有相同标识符的卡片时,卡片布局的默认行为是什么。例如,如果添加了panel1。稍后在程序中,我添加了具有相同字符串标识符的panel2。在卡组中用panel2 替换panel1 是默认行为吗? 谢谢

【问题讨论】:

标签: java swing indexing cardlayout


【解决方案1】:

下面是由addLayoutComponent(Component comp, Object constraints) 执行的addLayoutComponent()CardLayout's 实现。

public void addLayoutComponent(String name, Component comp) {
    synchronized (comp.getTreeLock()) {
        if (!vector.isEmpty()) {
            comp.setVisible(false);
        }
        for (int i=0; i < vector.size(); i++) {
            if (((Card)vector.get(i)).name.equals(name)) {
                ((Card)vector.get(i)).comp = comp;
                return;
            }
        }
        vector.add(new Card(name, comp));
    }
}

CardLayout 维护Card 对象的向量(见下文)。看起来当检测到名称冲突时,Card 中具有相同名称的Component 被替换为新添加的Component。因此,具有特定名称的 show() 将显示以该名称添加的 last 组件。

class Card implements Serializable {
    static final long serialVersionUID = 6640330810709497518L;
    public String name;
    public Component comp;
    public Card(String cardName, Component cardComponent) {
        name = cardName;
        comp = cardComponent;
    }
}

【讨论】:

    【解决方案2】:

    可以添加多张具有相同标识符的卡片。您可以[编辑]仍然[/edit]导航到bothshow(Container, String) 显示添加的面板 [edit]firstlast[/edit]。

    卡斯帕

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-13
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多