【发布时间】:2016-02-02 06:56:09
【问题描述】:
语言: 爪哇
目标: 离开屏幕后重新出现的动画圆圈
问题: getWidth() 在 buildGUI 方法(及其类)之外不起作用
问题: 如何找到框架的宽度并在 buildGUI 方法之外使用它?
审核: Java, JFrame: getWidth() returns 0 getHeight() and getWidth() method Why can't I access my panel's getWidth() and getHeight() functions?
我也试过: 1:使用 Ballroom.HEIGHT 和 Ballroom.WIDTH 错误地返回值 1。 2:通过参数传递帧大小。正如预期的那样,这仅给出了帧大小的初始值。 3:公开课。 4:尝试 Ballroom.getWidth() 或 frame.getWidth() 以及此方法的其他变体。
代码: 我认为相关的代码部分。
这部分是我不能使用getWidth()的地方。
public void step() { //this is inside: class Ball
if (y >= getHeight) { //relocate objects
vert = false;
y = x;
x = 0;
}
}
这部分构建了 GUI。它在里面:class Ballroom extends JPanel implements ActionListener {
void buildIt() {
frame = new JFrame("Ballroom");
frame.add(this);
timer = new Timer(100, this);
blink = new Timer(200, this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
//initialize balls
ball = new Ball(getWidth() / 2, 20, gw());
ball2 = new Ball(getWidth() / 2 + 80, 20, gw());
ball3 = new RedBall(getWidth() / 2 - 80, 20, gw());
ball4 = new BlinkingBall(getWidth() / 2 - 40, 20, gw());
timer.start();
blink.start();
System.out.println(gw());
}
【问题讨论】:
-
可能是
ComponentListener,代表example。 -
你能展示更多你的代码吗?在
Ball类中创建Ballroom的实例的位置并不明显。 -
到底是什么问题?你是什么意思是“不能使用getWidth()”?不允许吗?不知道怎么办?