Yegoshin Maxim
Yegoshin Maxim

Reputation: 881

Java. Swing. Changing of component's order in a container

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?

Upvotes: 1

Views: 6229

Answers (5)

Sonny Benavides
Sonny Benavides

Reputation: 53

You can change the order to add every component:

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

Upvotes: 0

Alberto Starosta
Alberto Starosta

Reputation: 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();

Upvotes: -1

Christoph Walesch
Christoph Walesch

Reputation: 2427

If you don't want the hierarchy events and others to fire, I think the only option is to customize the layout manager.

Upvotes: 1

StanislavL
StanislavL

Reputation: 57401

Try CardLayout. It allows component switching.

Upvotes: 0

MByD
MByD

Reputation: 137382

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:

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();

Upvotes: 4

Related Questions