/* Example of handling component change events to control the minimum and maximum size of a contentPane (JFrame). Also shows the use of MatteBorder. Borders replace insets as the way to have spacing inside containers. Mike Barnes 9/20/04 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class ComponentResize extends JFrame { public ComponentResize(String title){ super(title); // add ComponentListener to deal with window resize events addComponentListener(new ControlWindowSize()); // Borders replace insets in containers. // For the JFrame the borders are set via the JRootPane.... Insets insets = new Insets(5, 5, 5, 5); JRootPane rp = getRootPane(); rp.setBorder(new MatteBorder(insets, Color.lightGray)); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout(5, 5)); JButton b = new JButton("north"); b.setBackground(Color.pink); contentPane.add(b, BorderLayout.NORTH); b = new JButton("south"); b.setBackground(Color.red); contentPane.add(b, BorderLayout.SOUTH); b = new JButton("center"); b.setToolTipText("try resizing the frame small and very large"); b.setBackground(Color.cyan); contentPane.add(b, BorderLayout.CENTER); b = new JButton("east"); b.setBackground(Color.yellow); contentPane.add(b, BorderLayout.EAST); b = new JButton("west"); b.setBackground(Color.orange); contentPane.add(b, BorderLayout.WEST); System.out.println(contentPane.getInsets()); } class ControlWindowSize extends ComponentAdapter { public void componentResized(ComponentEvent e) { int width, height; JFrame source = (JFrame) e.getSource(); Dimension d = new Dimension(source.getSize()); width = (int) d.getWidth(); height = (int) d.getHeight(); if (width < 300) width = 300; else if (width > 500) width = 500; else if (height < 200) height = 200; else if (height > 500) height = 500; else return; source.setSize(new Dimension(width, height)); } } public static void main(String [] args){ ComponentResize app = new ComponentResize("JFrame size control"); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.pack(); app.setVisible(true); } }