Within Swing you’re supposed to be able to specify the minimum size for a frame with a simple call. For instance, assume that I made a frame that extends JFrame. Consider adding the following line to the constructor:

setMinimumSize(new Dimension(600,400));

This specifies that the frame should never shrink below 600 by 400 pixels in size. Great, huh? The problem is it doesn’t work:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4320050

And it hasn’t worked since Java 1.2. And the only reason I don’t think it was a problem prior to that is that it wasn’t part of JDK 1.1 or 1.0. However there is a way to get around it; overriding the paint() method.

The paint() method is part of the java.awt.Container package. And it’s called when a container needs to be repainted. We just need to override that event, and stop the event when the minimum width and height that are specified are reached. If and the repaint needs to occur you need to call the repaint() methods for any containers within the frame (such as JPanels, etc). I’ve adopted the code that’s in the bug report I mentioned above. Try it in your own GUI apps.

Fortunately this won’t be an issue too much longer – this bug was finally fixed in Java 6, due out Real Soon Now ™.

        public void paint(Graphics g) {
               double w = getSize().getWidth();
               double h = getSize().getHeight();

               if (w < 600 && h < 400) {
                       setVisible(false);
                       setSize(600, 400);
                       setVisible(true);
                       return;
               } else if (w < 600) {
                       setVisible(false);
                       setSize(600, (int) h);
                       setVisible(true);
                       return;
               } else if (h < 400) {
                       setVisible(false);
                       setSize((int) w, 400);
                       setVisible(true);
                       return;
               }

               jPanel1.repaint(); // Components are on this panel
               statusBar.repaint(); //I also have a JXStatusBar

               if (!firsttime) // Set to 'true' in frame constructor
               {
                       jPanel1.validate();
               } // so that validate() isnt called
               else // immediately on frame.show()
               {
                       firsttime = false;
               }
       }