Search code examples
javaswinglayoutboxlayout

Reordering elements in BoxLayout


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


Solution

  • 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