Search code examples
javaswinglayout-managerflowlayout

How to auto resize JFrame when elements move on next line using FlowLayout


While you resize JFrame manually via mouse, elements on JPanel can go on next line if there is no enough space, same time new element-lines can be removed if JFrame is big enough

Example:

at this moment there are two lines to fit all JButtons enter image description here

If I change JFrame width via mouse, JButtons will drop on next lines:

enter image description here

the problem is you can't see all JButtons, JFrame needs to be resized in height.

How to make JFrame auto resize in height to fit all elements according to set width?


Solution

  • This is not a very good design. Show me another professional application that works like this? People don't like to see the size of frames jump. The user is usually resizing the frame to fit the app on their desktop and will get frustrated if they fix the width and the height changes. Let the user control the size.

    If you want all the buttons to display, then maybe a better solution is to just make the frame non resizable by using:

    frame.setResizable( false );
    frame.pack();
    frame.setVisible();
    

    Anyway, if you really want to do this then you would probably add a ComponentListener to the content pane of the frame. Then in the componentResized() method you would invoke pack().

    However, this will cause multiple events to be generated every couple of pixels so you may also want to use:

    Toolkit.getDefaultToolkit().setDynamicLayout( false );
    

    So that the pack() is only done once when the mouse is released.