我曾多次因建议使用以下方法而受到批评:
setPreferredSize()
setMinimumSize()
setMaximumSize()
在 Swing
组件上。当我想定义显示组件之间的比例时,我没有看到任何替代方法。有人告诉我:
With layouts the answer is always the same: use a suitable LayoutManager.
我在网上搜索过,但没有找到任何对该主题的全面分析。所以我有以下问题:
- 我应该完全避免使用这些方法吗?
- 这些方法的定义是有原因的。那么我应该什么时候使用它们呢?在什么情况下?出于什么目的?
- 使用这些方法到底会产生哪些负面后果? (我只能考虑在不同屏幕分辨率的系统之间添加可移植性)。
- 我认为没有任何 LayoutManager 能够完全满足所有所需的布局需求。我真的需要为布局上的每一个小变化实现一个新的 LayoutManager 吗?
- 如果4的答案是"is",这是否会导致LayoutManager类激增而变得难以维护?
- 如果我需要定义组件子组件之间的比例(例如,child1 应使用 10% 的空间,child2 40%,child3 50%),是否可以在不实现自定义 LayoutManager 的情况下实现这一目标?
最佳答案
-
Should I completely avoid the use of those methods?
对于应用程序代码是的。
-
The methods have been defined for a reason. So when should I use them? In which context? For what purposes?
我不知道,我个人认为这是一个 API 设计意外。稍微受到对子尺寸有特殊想法的复合组件的影响。 “稍微”,因为他们应该使用自定义的 LayoutManager 来实现他们的需求。
-
What exactly are the negative consequences of using those methods? (I can only think adding portability between systems with different screen resolution.)
例如,Rules (hehe) 中提到了一些(不完整,不幸的是,由于 SwingLabs 迁移到 java.net,链接已损坏)技术原因。或在 link @bendicott 在他/她对 my answer 的评论中发现。在社交方面,给你不幸的同事带来大量的工作,他必须维护代码并找到损坏的布局。
-
I don't think any LayoutManager can exactly satisfy all desired layout needs. Do I really need to implement a new LayoutManager for every little variation on my layout?
是的,有足够强大的布局管理器来满足“所有布局需求”的非常好的近似。三大布局是 JGoodies FormLayout、MigLayout、DesignGridLayout。所以不,在实践中,除了简单的高度特化的环境之外,您很少编写 LayoutManager。
-
If the answer to 4 is "yes", won't this lead to a proliferation of LayoutManager classes which will become difficult to maintain?
(4的答案是“否”。)
-
In a situation where I need to define proportions between children of a Component (for example, child 1 should use 10% of space, child 2 40%, child 3 50%), is it possible to achieve that without implementing a custom LayoutManager?
三巨头中的任何一个都可以,甚至 GridBag 都不能(从来没有费心去真正掌握,太麻烦,太少力量)。
关于java - 我应该避免在 Java Swing 中使用 set(Preferred|Maximum|Minimum) 大小方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29451863/