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.
There 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:
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);
}
}
wguruBy Anonymous on November 22, 2009, 7:13 am..in extremely unappreciated and otherwise needlessly over sized windows.
Reply | Read entire comment
How to set a minimum window sizeBy Anonymous on November 22, 2009, 7:07 amIf this article still holds true for current (2009) Vista's Windows systems Home premium, etc.), perhaps someone would detail what a user is supposed to do with...
Reply | Read entire comment
View all comments