如何在buildGUI方法之外使用getWidth和getHeight?

时间:2015-11-02 11:44:22

标签: java swing

语言: 爪哇

目的: 动画在离开屏幕后重新出现的圆圈

问题: 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。它在里面:类舞厅扩展JPanel实现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());
}

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。

关键是将参数frame f或panel p添加到step(),然后使用buildGUI方法在类中调用step(frame)。 之后我可以调用f.getWidth()或p.getWidth(和getHeight())。