java setSize() v/s setPreferredSize() 和 pack()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6384702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:41:24  来源:igfitidea点击:

setSize() v/s setPreferredSize() and pack()

javaswinguser-interface

提问by program-o-steve

I am not clear about what is the difference between setSize()and setPreferredSize(). what would happen if i use setSize()instead of setPreferredSize().

我不清楚setSize()和之间有什么区别setPreferredSize()。如果我使用setSize()而不是setPreferredSize().



And what exactly does pack()method do ?

pack()方法究竟是做什么的?

回答by Suhail Gupta

Calling pack()on a window will size it based on the preferredSize of its containing components. It will be as small as possible but taking into account the preferredSize and layout of its components. If you just randomly use frame.setSize(), then the components added to the content pane will expand/contract to fit the space available, which means the preferred size of each component may be overridden.

调用pack()窗口将根据其包含组件的 preferredSize 来调整它的大小。它会尽可能小,但要考虑到它的组件的首选大小和布局。如果您只是随机使用frame.setSize(),那么添加到内容窗格的组件将扩展/收缩以适应可用空间,这意味着每个组件的首选大小可能会被覆盖。

setSize()sets the size of the component and setPreferredSizesets the preferred size.The Layoutmanager will try to arrange that much space for your component. It depends on whether you're using a layout manager or not ...

setSize()设置组件的大小并setPreferredSize设置首选大小。布局管理器将尝试为您的组件安排那么多空间。这取决于您是否使用布局管理器...

See Java: Difference between the setPreferredSize() and setSize() methods in components

请参阅Java:组件中 setPreferredSize() 和 setSize() 方法之间的区别