【问题标题】:How to use getWidth and getHeight outside of the buildGUI method?如何在 buildGUI 方法之外使用 getWidth 和 getHeight?
【发布时间】: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()”?不允许吗?不知道怎么办?

标签: java swing


【解决方案1】:

我找到了解决办法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-02
    • 2011-09-02
    • 1970-01-01
    • 2013-03-30
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多