1

I have a BoxLayout (Y_AXIS) with some (FlowLayout) elements already added like so:

element1> ================= <element1
element2> ================= <element2
element3> ================= <element3

Just wondering if there is a simple way to swap these elements positions in the layout. i.e. I might want to move element3 up and element2 down.

Is there anything like:

element3.setPosition(element2,ABOVE);

Thanks

EDIT: found this solution. Gonna give it a go now

Community
  • 1
  • 1
user1270235
  • 359
  • 3
  • 4
  • 11

2 Answers2

3

Is there anything like...

You can make your own method to do that by using:

panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();

Cehck out the Container API for more details about those methods.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • but the problem there is that it still just adds them to the bottom of the list. I would have to replace all of the elements within the two "moving" panels which would probably get a but messy.. – user1270235 Apr 09 '14 at 05:08
  • @user1270235, as I said please read the API. There is more than one method signature for the add(...) method. The `add(component, int)` method allows you to specify the insertion position of the component. Having said that, madprogrammer's suggestion to use the ZOrder would be easier. – camickr Apr 09 '14 at 05:24
3

You could consider using Container#setComponentZOrder

This will allow you to change the order in which components appear in the container (physically changing the order in which they are rendered and laid out)

int index = getComponentZOrder(element3);
setComponentZOrder(element3, --index);

Just beware, you can't set the zorder below 0 or above getComponentCount() - 1

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • +1, nice suggestion, the remove/add is done in one statement, just by changing the ZOrder. – camickr Apr 09 '14 at 05:16
  • Great Answer! works great. was not aware of this. Thanks – user1270235 Apr 09 '14 at 05:20
  • @user1270235 It's kinda funky but gets the job done ;) – MadProgrammer Apr 09 '14 at 05:21
  • @user1270235, I hope you read the API to actually understand what this method does because it is just a byproduct of the way Swing paints components that this happens to work. The ZOrder is actually used to control the "stacking of components" on top of one another. – camickr Apr 09 '14 at 05:23