我可以找到很多问题来解决如何获得不包含边界的JFrame“真实”尺寸的问题,但这是不同的:我有一个带有一些内容的JFrame ,我想设置JFrame的最小大小,以便其内容窗格不能小于这些内容的大小。简单地做类似根据内容的大小设置帧的最小尺寸
setMinimumSize(getContentPane().getPreferredSize())
不工作,当然,由于帧的大小结合其边界,任何菜单栏等 - 所以你仍然会能够缩小框架下足够小,部分内容被剪辑。所以,我想出了这个解决方案,而不是:
// Set minimum size so we can't resize smaller and hide some of our
// contents. Our insets are only available after the first call to
// pack(), and the second call is needed in case we're too small.
pack();
Dimension contentSize = getContentPane().getPreferredSize();
Insets insets = getInsets();
Dimension minSize = new Dimension(
contentSize.width + insets.left + insets.right,
contentSize.height + insets.top + insets.bottom +
(getJMenuBar() != null ? getJMenuBar().getSize().height : 0));
setMinimumSize(minSize);
pack();
这似乎工作,但感觉非常哈克,特别是与假设专用于装饰唯一可能的空间将通过插图和被考虑潜在的菜单栏(只影响高度)。当然有更好的解决方案,对吧?
如果没有,那么希望下次有人遇到此问题时,他们将能够找到我的解决方法。 :)
'frame.pack()'它。 – winterfox