Java JFrame handle resize event and set minimum size

Description

Java JFrame handle resize event and set minimum size


import java.awt.Window;
import java.awt.event.ComponentAdapter;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

class MinSizeComponentListener extends ComponentAdapter {
   private Window window;
   private int minHeight;
   private int minWidth;

   MinSizeComponentListener(Window frame, int minWidth, int minHeight) {
       this.window = frame;
       resetSizes(minWidth, minHeight);//from  w  w w.  j  a  v a 2s.c  o  m
   }

   public void resetSizes(int minWidth, int minHeight) {
       this.minWidth = minWidth;
       this.minHeight = minHeight;
       adjustIfNeeded(window);
   }

   @Override
   public void componentResized(java.awt.event.ComponentEvent evt) {
       adjustIfNeeded((Window) evt.getComponent());
   }

   private void adjustIfNeeded(final Window window) {
       boolean doSize = false;
       int newWidth = window.getWidth();
       int newHeight = window.getHeight();
       if (newWidth < minWidth) {
           newWidth = minWidth;
           doSize = true;
       }
       if (newHeight < minHeight) {
           newHeight = minHeight;
           doSize = true;
       }
       if (doSize) {
           final int w = newWidth;
           final int h = newHeight;
           SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   window.setSize(w, h);
               }
           });
       }
   }
}
public class Main {
   public static void main(String[] args) {
      JFrame f = new JFrame();

      f.addComponentListener(new MinSizeComponentListener(f, 200,200));

      f.setSize(310, 200);
      f.setLocationRelativeTo(null);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }
}



PreviousNext

Related