Java 获取构造函数中JComponent的高度和宽度

Java 获取构造函数中JComponent的高度和宽度,java,swing,jframe,jcomponent,Java,Swing,Jframe,Jcomponent,我想得到我的JFrame的高度和宽度,这样即使调整了窗口的大小,图形也应该处于相同的相对位置。为此,我尝试在构造函数中获取高度和宽度,但它总是返回0。最好的方法是什么 public class FireworkComponent extends JComponent { public FireworkComponent() { //some variables .... this.getHeight(); this.getWidth(); } }尝试调用pack(

我想得到我的JFrame的高度和宽度,这样即使调整了窗口的大小,图形也应该处于相同的相对位置。为此,我尝试在构造函数中获取高度和宽度,但它总是返回0。最好的方法是什么

public class FireworkComponent extends JComponent {
   public FireworkComponent() {
   //some variables ....

  this.getHeight();
  this.getWidth();
    }

}尝试调用
pack()getHeight()之前的code>
getWidth()

如果组件未实现(即可见),尺寸将返回
0
。如果覆盖组件的
paintComponent
方法,则可以通过在组件的
Graphics
对象上绘制来检索容器的尺寸并在特定位置设置图形。

不要尝试在构造函数中获取它,请使用this.HEIGHT和this.WIDTH并将其设置为

公共void setLocation(intx,inty)方法。确保在应该覆盖的paintcomponent方法中执行此操作,以便每次重新调整其大小时调用它