我正在使用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();
但在我看来,组件正在被重新创建,因为它们在进行此类操作之前失去了一些处理程序(侦听器)。 您能建议另一种重新排序容器中组件的方法吗?
您问题中的问题是我们不知道 targetComponent 和 transferComponent 是谁,并且您可能创建了新组件。你可以试试这个:
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();
如果您不想触发层次结构事件和其他事件,我认为唯一的选择是自定义布局管理器。
尝试卡片布局。它允许组件切换。
您可以更改添加每个组件的顺序:
panel.add(componentIndex0);
panel.add(componentIndex1);
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();