gpt4 book ai didi

java - 设置窗口内部区域的大小

转载 作者:行者123 更新时间:2023-11-30 03:26:55 25 4
gpt4 key购买 nike

我有一个简单的函数,可以生成包含图像的 JFrame:

 //The window
JFrame frame = new JFrame();
//Topmost component of the window
Container main = frame.getContentPane();
//Turns out this is probably the simplest way to render image on screen
//with guaranteed 1:1 aspect ratio
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
//Put the image drawer in the topmost window component
main.add(panel);
//Set window size to the image size plus some padding dimensions
frame.setSize(image.getWidth(null)+1, image.getHeight(null)+15);

frame.setVisible(true);

结果:

image description

我认为发生这种情况是因为窗口尺寸包括顶部栏和窗口边框的大小。

我还尝试设置 JPanel 的大小并在 JFrame 上调用 pack():

 //Set the size to the panel and let JFrame size itself properly
panel.setSize(image.getWidth(null), image.getHeight(null));
frame.pack();

结果更糟:

image description

那么如何精确指定内部窗口尺寸(以像素为单位)?

image description

Here's the full function code.

最佳答案

通过重写 JPanelgetPreferredSize 方法并在 JFrame< 上调用 pack() 来指定面板的首选大小 使其可见之前

JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
@Override
public Dimension getPreferredSize(){
return new Dimension(image.getWidth(), image.getHeight());
}
};

请参阅 Use of overriding getPreferredSize() instead of using setPreferredSize() for fixed size Components 中的答案关于此技术或 setPreferredSize 方法的使用和效果

关于java - 设置窗口内部区域的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29991803/

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