2016-01-29 119 views
0

我可以找到很多问题来解决如何获得不包含边界的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(); 

这似乎工作,但感觉非常哈克,特别是与假设专用于装饰唯一可能的空间将通过插图和被考虑潜在的菜单栏(只影响高度)。当然有更好的解决方案,对吧?

如果没有,那么希望下次有人遇到此问题时,他们将能够找到我的解决方法。 :)

+1

'frame.pack()'它。 – winterfox

回答

5

你想要的最小尺寸只是你做初始包()后的帧大小;

frame.pack(); 
frame.setMinimumSize(frame.getSize()); 
+0

为什么我没有想到这一点?比我的解决方案好得多。 – chris

相关问题