Wizard API updated!
Tim Boudreau has released a new version of the Swing Wizard library (version 0.997) that fixes the WizardException bug reported in JavaWorld's recent Open Source Java Project profile. The article's examples have been reworked to test out the new, improved WizardException. Thanks, Tim, for this helpful fix!
Open Source Java Projects: The Wizard API

Newsletter sign-up

Sign up for our technology specific newsletters.

Enterprise Java
View all newsletters

Email Address:

Set a window's minimum size?

Use event listeners to enforce the minimum size of a window

QIs there a clean way to set a minimum size for a window? I want users to be able to enlarge my application window, but not make it smaller than a certain minimum size. I looked at APIs on the JFrame hierarchy and couldn't find anything I could use. Any help would be greatly appreciated.

AThere is no single method to create a minimum size for a window. However, you can enforce a minimum size by using event listeners. Whenever a resize event is received, check the size of the window and, if it is below the specified minimum, resize it back.

Here is the code:

Author Bio

Random Walk Computing is the largest Java/CORBA consulting boutique in New York, focusing on solutions for the financial enterprise. Known for their leading-edge Java expertise, Random Walk consultants publish and speak about Java in some of the most respected forums in the world.
import javax.swing.*;
import java.awt.event.*;
public class MinSizeFrame extends JFrame implements ComponentListener {
        static final int WIDTH = 400;
        static final int HEIGHT = 400;
        static final int MIN_WIDTH = 300;
        static final int MIN_HEIGHT = 300;
        public MinSizeFrame() {
                setSize(WIDTH, HEIGHT);
                addComponentListener(this);
        }
        public void componentResized(ComponentEvent e) {
           int width = getWidth();
           int height = getHeight();
         //we check if either the width
         //or the height are below minimum
         boolean resize = false;
           if (width < MIN_WIDTH) {
                resize = true;
                width = MIN_WIDTH;
         }
           if (height < MIN_HEIGHT) {
                resize = true;
                height = MIN_HEIGHT;
           }
         if (resize) {
               setSize(width, height);
         }
        }
        public void componentMoved(ComponentEvent e) {
        }
        public void componentShown(ComponentEvent e) {
        }
        public void componentHidden(ComponentEvent e) {
        }
        public static void main(String args[]) {
                MinSizeFrame f = new MinSizeFrame();
                f.setVisible(true);
        }
}


Resources