java - 调整大小时强制 JComponent 为正方形

标签 java swing resize jcomponent

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

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

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

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

我已经使用 SpringLayout 将它添加到内容 Pane 中:

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

因此它被限制在南北方向,以便在调整大小时调整其高度,东边被限制在内容 Pane 的边缘,但西边可以自由向左移动。

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

最佳答案

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

所有调整大小/定位方法(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);
}

关于java - 调整大小时强制 JComponent 为正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3489641/

相关文章:

java - Vert.x 使用 BLOB 和 hibernate 对来自数据库的数据进行分块回答

java - .等于表现得很有趣

java - 图像适配器无法初始化 ImageView

java - 如何转发参数列表

Java按钮反转

java - 在 Java GUI 中提供是/否选项

java - 我怎样才能最好地在 Swing 中实现淡入淡出按钮效果?

notifications - splitApp 中的 SAPUI5 通知栏

c - 防止控制台窗口在 C 中调整大小/滚动 (Window.h)

wpf - 当窗口最大化到与窗口相同的部分时调整 WPF 网格的大小