在Java语言中,有没有可能获得没有标题和其他边框的JFrame的宽度和高度?
frame.getWidth()和frame.getHeight()1似乎返回了包括边框在内的宽度。
谢谢。
发布于 2018-08-17 20:10:28
下面是一个可以在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。
https://stackoverflow.com/questions/5097301
复制相似问题