1

Language: Java

Aim: Animate circles that reappear after they leave the screen

Problem: getWidth() does not work outside of the buildGUI method (and its class)

Question: How do you find the width of the frame and use it outside of the buildGUI method?

Reviewing: Java, JFrame: getWidth() returns 0 getHeight() and getWidth() method Why can't I access my panel's getWidth() and getHeight() functions?

I also tried: 1: using Ballroom.HEIGHT and Ballroom.WIDTH which incorrectly returned value 1. 2: passing frame size through a parameter. As expected, this only gave the initial values of the frame size. 3: making classes public. 4: trying Ballroom.getWidth() or frame.getWidth() and other variations of this approach.

code: The part of my code that I think is relevant.

This part is where I can't use getWidth().

public void step() { //this is inside: class Ball

    if (y >= getHeight) { //relocate objects
        vert = false;
        y = x;
        x = 0;
    }

}

This part builds the GUI. it's inside: 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());
}
Community
  • 1
  • 1
Alain Lifmann
  • 137
  • 2
  • 9

1 Answers1

0

I found the solution.

The key is to add a parameter frame f or panel p to step() and then call step(frame) in the class with the buildGUI method. after that I was able to call f.getWidth() or p.getWidth (and getHeight()).

Alain Lifmann
  • 137
  • 2
  • 9