Search code examples
javaswinglayout-managerflowlayout

Make all but 1 element float left FlowLayout


I've got all my FlowLayout elements set to float left:

setLayout(new FlowLayout(FlowLayout.LEFT));

but I want the one on the end (right hand side) to float to the right, how can I make all but one float left?


Solution

  • FlowLayout doesn't support that feature.

    You can use a horizontal BoxLayout and add glue before the last component. See the section on Using Invisible Components from the Swing tutorial on How to Use BoxLayout for more information.

    One problem with the BoxLayout is that is doesn't automatically leave a space between components so you would also need to add a Box.createHorizontalStrut(...) for each space.

    Or another option is to create a second panel that uses a BorderLayout. Then you would add your panel with the flowLayout to the LINE_START and then add the last component to the LINE_END. You would probably also need to add an EmptyBorder to this component to provide proper spacing.