2

I have a JFrame which cannot be smaller than a specific size, or the elements cannot lay out properly.

I tried to setMinimumSize() and overwrite the getMinimumSize() method of this frame, but I can still resize the frame to smaller.

So, must I listen to the change of bounds in my componentListener when componentResized(), and if it's smaller, set it back to normal size with setBounds()?

WesternGun
  • 11,303
  • 6
  • 88
  • 157
  • It should have worked. At least, it works here on linux. Cf http://stackoverflow.com/questions/2781939/setting-minimum-size-limit-for-a-window-in-java-swing?rq=1 for already discussed – Laurent G Mar 22 '17 at 16:16
  • Yes, thanks for the link. Now with this question asked, we have a better solution from Andrew. – WesternGun Mar 23 '17 at 08:16

2 Answers2

8

With the lack of compilable code, it is hard to tell what is going wrong there / in your code. Possibly the call the setMinimumSize(..) is occurring at the wrong time and/or with the wrong values.

Here, this code will not allow the frame to go smaller than it first appears, but will allow the user to drag it larger. Check the comments for tips.

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class MinimumSizeFrame {

    private JComponent ui = null;

    MinimumSizeFrame() {
        ui = new JPanel(new BorderLayout(4,4));

        JLabel label = new JLabel("Text in big label");
        label.setBorder(new EmptyBorder(40, 100, 40, 100));
        ui.add(label);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            MinimumSizeFrame o = new MinimumSizeFrame();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            // have the JVM calculate the ideal size of this GUI
            f.pack(); 
            // now use THAT as minimum size!
            f.setMinimumSize(f.getSize()); 

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    OK, call `setMinimumSize()` after `pack()`. That's working in my situation. It picks some confidence back of me about Java Swing. Thanks a lot! – WesternGun Mar 23 '17 at 08:14
1

You may try using below property in frame initialisation to avoid resizing

setResizable(false);
mhasan
  • 3,703
  • 1
  • 18
  • 37