Java。摇摆。更改容器中组件的顺序

问题描述 投票:0回答:5

我正在使用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
5个回答
4
投票

您问题中的问题是我们不知道 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();

1
投票

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


0
投票

尝试卡片布局。它允许组件切换。


0
投票

您可以更改添加每个组件的顺序:

panel.add(componentIndex0);
panel.add(componentIndex1);

-1
投票
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();
© www.soinside.com 2019 - 2024. All rights reserved.