2

我有一个 JComponent 进行自定义绘图,并覆盖以下方法:

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

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

其中 imageWidth 和 imageHeight 是图像的实际大小。

我已使用 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);

所以它被限制在北方和南方,这样它在调整大小时会调整它的高度,东方被限制在内容窗格的边缘,但西方可以自由地向左移动。

我希望它在调整大小时保持正方形大小(宽度 == 高度)。任何人都知道如何做到这一点?

4

1 回答 1

3

最小/首选/最大尺寸只是布局管理器的提示。要强制使用特定尺寸,您需要覆盖组件中的尺寸处理。

所有调整大小/定位的方法(setHeight、setLocation、setBounds 等)最终都会调用reshape. 通过在组件中重写此方法,您可以强制组件为方形。

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);
}
于 2010-08-15T23:31:29.873 回答