Search code examples
javaswingjava-2d2d-games

Calling a method from GamePanel


I believe this is a pretty simple OO question but I can't seem to find the answer :/ I have a game panel where a load of balls are painted onto a panel. When a ball hits the bottom of the panel a Game Over message should be displayed.

The problem which I'm dealing with is regarding this Game Over JOptionPane. I believe it should be kept in this class but I need to call it in the Ball class.

Here is the part of Ball class where I want to call the method (marked with **):

private void moveBall() {

    if (x == panel.getWidth() - size) {
        xa -= speed;
    } else if (x < 0) {
        xa += speed;
    }

    if (y == panel.getHeight() - size) {
        ya -= speed;
    } else if (y < 0) {
        ya += speed;
    }

    if (collision()) {
        ya = -speed;
        y = platform.getY() - DIAMETER;
    }

    if (y == panel.getHeight() - size) {

        // ***Call gameOver here***

    }
    x += xa;
    y += ya;
}

Here is the constructor being called from the ball class in my game panel:

// Constructor to pass a colour and a platform
public Ball(JFrame frame, JPanel panel, Platform platform, Color colour,
        int x, int y, int size) {

    this.platform = platform;

    this.frame = frame;
    this.panel = panel;
    this.colour = colour;

    // Location of the ball
    this.x = x;
    this.y = y;

    // Size of the ball
    this.size = size;

    animator = new Thread(this);
    animator.start();
}

So how do I get access to that method?

Note (Structure): Frame -> Panel -> Ball

Thanks

Let me know if I haven't explained myself well or you need more information


Solution

  • Consider watching the position of the ball from a different class, which has access to the gameOver function. This way you don't need to expose the panels to the Ball class, and your problem is avoided.

    Also, you can't call the gameOver function since it does not exist in JFrame, if you want to use this current approach, you need to supply the class, or an interface, which contains the gameOver function to the Ball constructor.