JFrame:获得没有边框的大小?

时间:2011-02-23 21:21:32

标签: java swing awt jframe

在Java中,是否可以获得没有标题和其他边框的JFrame的宽度和高度?

frame.getWidth()和frame.getHeight()1似乎返回包括边框的宽度。

感谢。

4 个答案:

答案 0 :(得分:35)


frame.getContentPane().getSize();

答案 1 :(得分:7)

frame.pack();
System.out.println("frame width : "+getWidth());
System.out.println("frame height: "+getHeight());
System.out.println("content pane width : "+getContentPane().getWidth());
System.out.println("content pane height: "+getContentPane().getHeight());
System.out.println("width  of left + right  borders: "+(getWidth()-getContentPane ().getWidth()));
System.out.println("height of top  + bottom borders: "+(getHeight()-getContentPane().getHeight()));

答案 2 :(得分:3)

这很好用

frame.getContentPane().getSize();

但是如果你还没有添加内容则不行。就我而言,我想在添加内容之前计算JFrame的内部维度,因此我可以相应地划分内容。这就是我想出来的。

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

pack(); // Need this, otherwise insets() show as 0.  
int scrW = (int)screenSize.getWidth();
int scrH = (int)screenSize.getHeight();
  int innerW = scrW - getInsets().left - getInsets().right;
  int innerH = scrH - getInsets().top - getInsets().bottom;

  // Need to setSize(), otherwise pack() will collapse the empty JFrame
  setSize(scrW, scrH);

答案 3 :(得分:0)

这是一个适用于JFrame和AWT的Frame(恰好是JFrame的超类型)的代码段:

public static Dimension getInnerSize(Frame frame) {
    Dimension size = frame.getSize();
    Insets insets = frame.getInsets();
    if (insets != null) {
        size.height -= insets.top + insets.bottom;
        size.width -= insets.left + insets.right;
    }
    return size;
}

当心:插图仅在显示框架后才有效。

这是解决此问题的另一个代码段:

private static Insets defaultInsets;
public static Insets getInsetsWithDefault(Frame frame) {
    // insets only correct after pack() and setVisible(true) has been
    // called, so we use some fallback strategies
    Insets insets = frame.getInsets();
    if (insets.top == 0) {
        insets = defaultInsets;
        if (insets == null) {
            insets = new Insets(26, 3, 3, 3);
            // usual values for windows as our last resort
            // but only as long as we never saw any real insets
        }
    } else if (defaultInsets == null) {
        defaultInsets = (Insets) insets.clone();
    }
    return insets;
}

此代码需要在可见的框架中调用一次。此后,假设它们始终相同,即使对于不可见的帧(由于defaultInsets的缓存),它也可以正确预测插入。

当然,这仅在所有窗口都具有相同的窗口装饰时才有效。但是我不知道它们在窗口之间可能会有所不同的任何情况。

这也可能有用:

frame.addWindowListener(new WindowAdapter() {

    @Override
    public void windowOpened(WindowEvent e) {
        MyUtilClass.getInsetsWithDefault(frame); // init the defaultInsets
    }

});

一旦窗口可见,它将调用getInsetsWithDefault()方法并初始化正确的defaultInsets