by Java Q&a Experts

Set a window’s minimum size?

news
Oct 5, 19992 mins

Use event listeners to enforce the minimum size of a window

Q: Is 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.

A: Here is the code:

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);
        }
}
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.