我有一个执行自定义绘图的 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/