本文介绍了调用setPreferredSize()后,getWidth()和getHeight()为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的项目上工作了几个小时,但对此一直感到沮丧.

I've been working on my project for a few hours now, only to be constantly frustrated at this.

我有一个父JFrame,它向其添加了一个JPanel,它将用于渲染和显示我正在开发的仿真.没有将要添加到JPanel的摆动对象,因为我将只使用它来使用图形对象渲染形状.

I have a parent JFrame that adds a JPanel to it, and it is going to be used for the rendering and display of my simulation I'm developing. There are no swing objects that are going to be added to the JPanel, as I will only be using it for rendering shapes using a graphics object.

我的代码如下:

public class SimulationPanel extends JPanel {

private BufferedImage junction;
private Graphics2D graphics;

public SimulationPanel() {
    super();
    initPanel();

}

private void initPanel() {
    this.setPreferredSize(new Dimension(600, 600)); //TODO: bug with not sizing the junction correctly.
    junction = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    graphics = junction.createGraphics();
    setBackground(Color.white);


    System.out.println(getWidth());
}

代码特别在我尝试创建新的BufferedImage的initPanel()方法的第二行中断.

The code specifically breaks on the second line of the initPanel() method where I try to create a new BufferedImage.

异常的输出状态为线程"AWT-EventQueue-0"中的异常java.lang.IllegalArgumentException:宽度(0)和高度(0)必须大于0"

The output from the exception states "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (0) and height (0) must be > 0"

我真的不确定为什么会这样.我曾尝试使用Stack Overflow的以往答案,但无法成功提供帮助.

I'm really unsure on why this is. I've tried to use past answers from Stack Overflow but they were unsuccessful in helping.

这是我的第一篇文章,所以我希望它还不错.

This is my first post, so I hope it isn't too bad.

谢谢.

推荐答案

设置首选大小时,您告诉各种Java布局管理器将面板添加到容器中后如何布置 .但是,直到将它实际添加到容器中之前,它都不会具有宽度或高度,即使在它添加之后,它也可能没有您要求的宽度和高度.

When you set the preferred size, you tell the various Java layout managers how you would like your panel to be laid out once it's added to a container. But until it actually is added to the container, it won't have a width or height, and even after it is, it might not have the width and height that you asked for.

一种选择是直接将600用作新缓冲图像的宽度和高度,并且在将面板添加到JFrame时,请确保在JFrame上调用pack()以允许窗口调整为首选大小面板的大小.

One option is to just use 600 directly for the width and height of your new buffered image, and when you add the panel to the JFrame make sure you call pack() on the JFrame to allow the window to size to the preferred size of your panel.

这篇关于调用setPreferredSize()后,getWidth()和getHeight()为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:40