我想获取 JFrame 的高度和宽度,以便即使调整窗口大小,图形也应该处于相同的相对位置。为此,我试图在构造函数中获取高度和宽度,但它始终返回 0。最好的方法是什么?
public class FireworkComponent extends JComponent {
public FireworkComponent() {
//some variables ....
this.getHeight();
this.getWidth();
}
}
我想获取 JFrame 的高度和宽度,以便即使调整窗口大小,图形也应该处于相同的相对位置。为此,我试图在构造函数中获取高度和宽度,但它始终返回 0。最好的方法是什么?
public class FireworkComponent extends JComponent {
public FireworkComponent() {
//some variables ....
this.getHeight();
this.getWidth();
}
}
0
如果组件未实现(即可见),尺寸将返回。如果您覆盖组件的paintComponent
方法,您将能够检索容器的尺寸并通过在组件的Graphics
对象上绘制来在特定位置设置图形。
pack();
在打电话之前尝试打电话getHeight();
或getWidth();
不要尝试在构造函数中使用 this.HEIGHT 和 this.WIDTH 并将其设置为
公共 void setLocation(int x, int y) 方法。确保在您应该覆盖的paintcomponent方法中执行此操作,以便每次调整大小时都会调用它。