gpt4 book ai didi

Java Odd pack() 行为

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:50:00 30 4
gpt4 key购买 nike

我的主要问题是设置 JFrame 时的以下代码:

public Frame(){
JPanel panel = new JPanel();
add(panel);
panel.setPreferredSize(new Dimension(200, 200));

pack(); // This is the relevant code
setResizable(false); // This is the relevant code

setVisible(true);
}

通过以下打印语句,我们收到错误的面板尺寸:

System.out.println("Frame: " + this.getInsets());
System.out.println("Frame: " + this.getSize());
System.out.println("Panel: " + panel.getInsets());
System.out.println("Panel: " + panel.getSize());

Output:
Frame: java.awt.Insets[top=25,left=3,bottom=3,right=3]
Frame: java.awt.Dimension[width=216,height=238]
Panel: java.awt.Insets[top=0,left=0,bottom=0,right=0]
Panel: java.awt.Dimension[width=210,height=210]

我发现将相关代码修改为以下内容可以解决问题:

public Frame(){
JPanel panel = new JPanel();
add(panel);
panel.setPreferredSize(new Dimension(200, 200));

setResizable(false); // Relevant code rearranged
pack(); // Relevant code rearranged

setVisible(true);
}

这会为我们的面板生成正确的尺寸(使用与之前相同的打印语句):

Frame: java.awt.Insets[top=25,left=3,bottom=3,right=3]
Frame: java.awt.Dimension[width=206,height=228]
Panel: java.awt.Insets[top=0,left=0,bottom=0,right=0]
Panel: java.awt.Dimension[width=200,height=200]

我查看了一些文档,但无法找出这 10 个像素的来源。有人知道为什么会这样吗?

最佳答案

JFrame 派生自 Frame,在 setResizable(...) 的 Frame 源代码中,您会看到以下注释:

    // On some platforms, changing the resizable state affects
// the insets of the Frame. If we could, we'd call invalidate()
// from the peer, but we need to guarantee that we're not holding
// the Frame lock when we call invalidate().

因此,在调用 setResizable(false) 之后调用 pack() 是有意义的。

关于Java Odd pack() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987646/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com