【问题标题】:Get height and width of JComponent in constructor在构造函数中获取JComponent的高度和宽度
【发布时间】:2011-11-09 19:00:08
【问题描述】:
我想获取我的 JFrame 的高度和宽度,以便即使调整窗口大小,图形也应该处于相同的相对位置。为此,我试图在构造函数中获取高度和宽度,但它始终返回 0。最好的方法是什么?
public class FireworkComponent extends JComponent {
public FireworkComponent() {
//some variables ....
this.getHeight();
this.getWidth();
}
}
【问题讨论】:
标签:
java
swing
jframe
jcomponent
【解决方案1】:
如果组件未实现(即可见),尺寸将返回 0。如果您覆盖组件的paintComponent 方法,您将能够通过在组件的Graphics 对象上绘制来检索容器的尺寸并在特定位置设置图形。
【解决方案2】:
在调用getHeight(); 或getWidth(); 之前尝试调用pack();
【解决方案3】:
不要试图在构造函数中使用 this.HEIGHT 和 this.WIDTH 并设置它
public void setLocation(int x, int y) 方法。确保在您应该覆盖的paintcomponent方法中执行此操作,以便每次调整大小时都会调用它。