[英]How to resize components related to panel in swing?
I want to resize child components related to its parent(Panel). 我想调整与其父级(Panel)相关的子组件的大小。
I am using the following method: 我使用以下方法:
@Override
public Dimension getPreferredSize() {
Dimension d = getParent().getSize();
int w = d.width * wid / 100;
int h = d.height * he / 100;
//System.out.println("x"+w+"h"+h);
return new Dimension(w,h);
}
But it doesn't solve my problem. 但它并没有解决我的问题。 Can anybody tell if there is another way to resize component?
任何人都可以告诉是否有另一种方法来调整组件大小?
use proper LayoutManager
, no reason to supply that 使用正确的
LayoutManager
,没有理由提供
in the case that you want to resize programaticaly, by refusing LayoutManager, then you have to implement ComponentListener or HierarchyListener 如果你想通过拒绝LayoutManager来调整programaticaly的大小,那么你必须实现ComponentListener或HierarchyListener
after any (above mentioned) changes you have to call revalidate() and repaint() 在任何(上面提到的)更改之后,你必须调用revalidate()和repaint()
if you want to resize from any Listener, delay resize (400-500 miliseconds) event by Swing Timer, if resize continue Timer#restart() to avoiding flickering or freeze, 如果你想从任何监听器调整大小,请通过Swing Timer延迟调整大小(400-500毫秒)事件,如果调整大小继续Timer#restart()以避免闪烁或冻结,
You can just call the setPreferredSize(Dimension d)
on the child components. 您可以在子组件上调用
setPreferredSize(Dimension d)
。 If you pack the JFrame, the components will try to become that size. 如果打包JFrame,组件将尝试变为该大小。
EDIT: As the comment said, it is best to avoid setPreferredSize(Dimension d)
, but I have had uses for the method. 编辑:正如评论所说,最好避免使用
setPreferredSize(Dimension d)
,但我已经使用了该方法。 For example: A JPanel with a BorderLayout, in which you have 3 JPanels (custom classes). 例如:带有BorderLayout的JPanel,其中有3个JPanel(自定义类)。 The WEST and SOUTH Panel (the other is CENTER) had to have a height of 0.1 * the width or the height respectively if the JPanel.
如果JPanel,WEST和SOUTH面板(另一个是CENTER)必须分别具有0.1 *宽度或高度的高度。 I used
我用了
setPreferredSize(new Dimension(getPreferredSize().height, getPreferredSize().width * 0.1))
which worked well. 效果很好。 The Borderlayout took that value, and made the Panel a bit wider (I had to do this because there were no other JComponents in any of the inner JPanels).
Borderlayout取得了这个值,并使Panel变得更宽(我必须这样做,因为在任何内部JPanel中都没有其他JComponents)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.