开发者

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 nor开发者_StackOverflow中文版th 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜