Java Swing的setXXXSize()有替代方法吗?

huangapple go评论60阅读模式
英文:

java swing setXXXSize() alternative?

问题

我总是在这里看到很多关于使用 setXxxSize() 方法来设置组件大小的线程,其中

Xxx=Preferred
Xxx=Maximum
Xxx=Minimum

或者只是一般情况下使用 setSize (),但是没有人在我们确实需要一个元素具有固定大小的情况下提出替代方法,而不考虑布局中的可用空间。
这里有什么可以遵循的最佳实践吗?

英文:

I always see many threads here how setting an components size using setXxxSize() method where

Xxx=Preferred
Xxx=Maximum
Xxx=Minimum

Or just setSize () in general are all bad ideas but nobody suggests an alternative when we do need an element to be of an fixed size regardless of available space in the layout.
Any best practices to be followed here?

答案1

得分: 3

  1. 覆盖重写 JComponentgetPreferredSize() 方法(首先检查 super 方法建议的大小,如果不合适)返回所需大小。
  2. 然后将组件放入布局中(例如 FlowLayout)或布局 + 约束中(例如 GridBagLayout 和适当的 GridBagConstraints),这将保持该大小(即不拉伸高度或宽度)。

另请参阅 在 Java Swing 中是否应避免使用 set(Preferred|Maximum|Minimum)Size 方法?

英文:
  1. Override getPreferredSize() of the JComponent to (first check the size suggested by the super method, and if not suitable) return the size required.
  2. Then put the component into a layout (e.g. FlowLayout) or layout + constraint (e.g. GridBagLayout & appropriate GridBagConstraints) which will honor that size (i.e. not stretch the height or width).

See also Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

huangapple
  • 本文由 发表于 2020年4月10日 11:05:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/61133423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定