I’m using java Swing. I’ve created JPanel and filled it with Components.
JPanel panel = new JPanel();
for (JComponent c : components) {
panel.add(c);
}
I need to change order of some components. For certainty, I need to swap two of the components with defined indexes(oldIndex and newIndex).
I know, I can obtain all of the components through panel.getComponents().
I’ve found only one way to do this.
Component[] components = panel.getComponents();
panel.removeAll();
components[oldIndex] = targetComponent;
components[newIndex] = transferComponent;
for (Component comp : components) {
panel.add(comp);
}
panel.validate();
But it seems to me, that components are being recreated, because they loose some handlers(listeners) they have before such manipulations.
Can you advise another way to reorder components in a container?
The problem in your question is that we don’t know who targetComponent and transferComponent are, and you might created new components. You can try this: