简体   繁体   English

根据内容大小设置框架最小尺寸

[英]Set frame minimum size based on size of contents

I can find plenty of questions tackling the issue of how to get the "real" size of a JFrame not counting its border, but this is different: I have a JFrame with some contents, and I want to set the JFrame's minimum size so that its content pane can't be smaller than the size of those contents. 我可以找到很多问题来解决如何获得JFrame的“实际”大小而不计算其边界的问题,但这是不同的:我有一个包含某些内容的JFrame,并且我想设置JFrame的最小大小以便其内容窗格不能小于这些内容的大小。 Simply doing something like 只是做类似的事情

setMinimumSize(getContentPane().getPreferredSize())

doesn't work, of course, because the frame's size incorporates its border, any menu bar, etc. -- so you'd still be able to shrink the frame down small enough that part of the contents get clipped. 当然,这是行不通的,因为框架的尺寸包含其边框,任何菜单栏等。因此,您仍然可以将框架缩小得足够小,以使部分内容被剪切。 So I came up with this solution instead: 因此,我想出了以下解决方案:

  // 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();

This appears to work, but it feels very hacky, in particular with the assumption that the only possible space dedicated for decorations will be taken into account via the insets and a potential menubar (which only affects the height). 这似乎可行,但感觉很棘手,特别是在假设将通过插图和可能的菜单栏(仅影响高度)来考虑装饰专用空间的前提下。 Surely there's a better solution, right? 当然有更好的解决方案,对吗?

If not, well, hopefully the next time someone has this problem, they'll be able to find my workaround solution. 如果没有,那么希望下次有人遇到此问题时,他们将能够找到我的解决方法。 :) :)

The minimum size you want is just the size of the frame AFTER you do the initial pack(); 您想要的最小大小就是刚进行初始pack()之后的帧大小;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM