Forcing a JComponent to be square when being resized

I have a JComponent that does custom drawing, and overrides the following methods:

public Dimension getPreferredSize() {
    return new Dimension(imageWidth, imageHeight);
}

public Dimension getMinimumSize() {
    return new Dimension(imageWidth, imageHeight);
}

Where imageWidth and imageHeight are the actual size of the image.

I have added it to the content pane using SpringLayout:

layout.putConstraint(SpringLayout.SOUTH, customComponent, -10, SpringLayout.SOUTH, contentPane);
layout.putConstraint(SpringLayout.EAST, customComponent, -10, SpringLayout.EAST, contentPane);
layout.putConstraint(SpringLayout.NORTH, customComponent, 10, SpringLayout.NORTH, contentPane);

So it is constrained to the north and south so that it will resize its height when it is resized, and the east is constrained to the edge of the content pane, but the west is free to move left.

I would like it to maintain a square size (width == height) when it is resized. Anyone have any idea how to do this?

Answer

The minimum/preferred/maximum sizes are only hints to the layout manager. To force a specific size, you will need to override the size handling in the component.

All resizing/positioning methods (setHeight, setLocation, setBounds etc…) ultimately call reshape. By overriding this method in your component, you can force the component to be square.

void reshape(int x, int y, int width, int height) {
   int currentWidth = getWidth();
   int currentHeight = getHeight();
   if (currentWidth!=width || currentHeight!=height) {
      // find out which one has changed
      if (currentWidth!=width && currentHeight!=height) {  
         // both changed, set size to max
         width = height = Math.max(width, height);
      }
      else if (currentWidth==width) {
          // height changed, make width the same
          width = height;
      }
      else // currentHeight==height
          height = width;
   }
   super.reshape(x, y, width, height);
}

Leave a Reply

Your email address will not be published. Required fields are marked *