调整大小时强制 JComponent 为方形
我有一个执行自定义绘图的 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);
因此它被限制在北部和南部,以便在调整大小时它会调整其高度,东部被限制在内容窗格的边缘,但西部是自由的向左移动。
我希望它在调整大小时保持正方形大小(宽度==高度)。有人知道如何做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最小/首选/最大尺寸只是对布局管理器的提示。要强制指定特定尺寸,您需要覆盖组件中的尺寸处理。
所有调整大小/定位方法(setHeight、setLocation、setBounds 等)最终都会调用
reshape
。通过在组件中重写此方法,您可以强制组件为正方形。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.