【问题标题】:Java. Swing. Changing of component's order in a container爪哇。摇摆。更改容器中组件的顺序
【发布时间】:2011-11-21 09:34:51
【问题描述】:

我正在使用 java Swing。我创建了 JPanel 并用组件填充它。

JPanel panel = new JPanel();
for (JComponent c : components) {
   panel.add(c);
}

我需要更改一些组件的顺序。可以肯定的是,我需要用定义的索引(oldIndex 和 newIndex)交换两个组件。 我知道,我可以通过panel.getComponents()获取所有的组件。

我只找到了一种方法。

Component[] components = panel.getComponents();
panel.removeAll();
components[oldIndex] = targetComponent;
components[newIndex] = transferComponent;
for (Component comp : components) {
    panel.add(comp);
}                
panel.validate();

但在我看来,组件正在重新创建,因为它们失去了在此类操作之前拥有的一些处理程序(侦听器)。 你能推荐另一种方法来重新排序容器中的组件吗?

【问题讨论】:

    标签: java swing containers


    【解决方案1】:

    您的问题是我们不知道 targetComponenttransferComponent 是谁,您可能会创建新组件。你可以试试这个:

    Component[] components = panel.getComponents();
    panel.removeAll();
    Component temp = components[oldIndex];
    components[oldIndex] = components[newIndex];
    components[newIndex] = temp;
    for (Component comp : components) {
        panel.add(comp);
    }                
    panel.validate();
    

    【讨论】:

    • 是的,你是对的。现在工作正常。非常感谢。知道这是相当愚蠢的路障=)对象是这样获得的: JImageButton targetBtn = (JImageButton) container.getComponentAt(dtde.getLocation());可转让 tr = dtde.getTransferable(); JImageButton transferBtn = (JImageButton) tr.getTransferData(JImageButtonTransferable.DEFAULT_JIMAGEBUTTON_FLAVOR);
    【解决方案2】:

    如果您不希望触发层次结构事件和其他事件,我认为唯一的选择是自定义布局管理器。

    【讨论】:

    • 诀窍是我想要它们。但是重新排序后这两个组件会丢失。
    【解决方案3】:

    试试CardLayout。它允许组件切换。

    【讨论】:

    • 我只能在 CardLayout 中看到“选择要显示的内容”逻辑。不知道如何在我的情况下使用它。我已经有了可以工作的组件,但这个重新排序问题仍未得到妥善解决。
    【解决方案4】:
    int oldIndex = -1;
    // old list holder
    ArrayList<Component> allComponents = new ArrayList<Component>();
    int idx = 0;
    for (Component comp : panel.getComponents()) {
      allComponents.add(comp);
      if (comp==com) {
        oldIndex = idx;
      }
      idx++;
    }
    
    panel.removeAll();
    
    // this is a TRICK !
    if (oldIndex>=0) {
      Component temp = allComponents.get(oldIndex);
      allComponents.remove(oldIndex);
      allComponents.add(newIndex, temp);
    }
    
    for (int i = 0; i < allComponents.size(); i++) 
      panel.add(allComponents.get(i));
    
    panel.validate();
    

    【讨论】:

    • afaics,这并不能解决需求(即交换两个组件)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多