我可以找到很多问题来解决如何获得JFrame的"实际"大小而不计算其边界的问题,但这是不同的:我有一个带有一些内容的JFrame,我想设置JFrame的最小大小,以便其内容窗格不能小于这些内容的大小.简单地做一些事情
setMinimumSize(getContentPane().getPreferredSize())
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为框架的大小包含其边框,任何菜单栏等 - 所以你仍然可以将框架缩小到足以使部分内容被剪裁.所以我想出了这个解决方案:
// 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();
Run Code Online (Sandbox Code Playgroud)
这看起来很有效,但感觉非常黑客,特别是假设通过插图和潜在的菜单栏(仅影响高度)将唯一可用于装饰的空间考虑在内.当然有更好的解决方案,对吧?
如果没有,那么,希望下次有人遇到这个问题时,他们将能够找到我的解决方案.:)