我正在使用 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();
关于 java 。 Swing 。更改容器中组件的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8209751/