2

I'm trying to develop a Java brick breaker (like DxBall) game and I want to make the Ball object with its own draw method.

What I'm trying to do:

public class Ball {
  private int x, y, diameter;
  public void  Ball(){
    x = 0;
    y = 0; 
    diameter = 20;
  }

  public void draw(Graphics g){
    g.setPaint(Color.red);
    g.fillOval(x, y, diameter, diameter);
  }
}

Therefore, my game engine extends JFrame and its paintComponent method will call game objects draw method. To sum, is it proper way to do object oriented game in Java? What should my Ball class extend?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • It depends on where do you want to apply this objects. – Roman C Nov 17 '12 at 16:05
  • I want to apply these objects in my GameEngine class which is a JFrame. GameEngine does some calculations and changes my objects(Ball or Paddle) x,y or speed values and then it will call all drawable objects paint methods. – user1832093 Nov 17 '12 at 16:18
  • No, you cannot call a paint method, call a draw method instead. – Roman C Nov 17 '12 at 16:22
  • Ok, look at [this](http://stackoverflow.com/questions/13164162/canvas-object-not-displaying-but-location-is-updating-correctly-in-java-applet/13166879#13166879) example my be this help you but it needs to convert to the light objects. – Roman C Nov 17 '12 at 16:33
  • For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Nov 17 '12 at 23:59

3 Answers3

3

If you wish to make Ball a graphical component, you could extend JComponent:

public class Ball extends JComponent {
    private int x;
    private int y
    private int diameter;

    public Ball() {
        x = 0; 
        y = 0; 
        diameter=20;
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setPaint(Color.red);
        g.fillOval(x, y, diameter, diameter);          
    }
}

and simply call repaint when you wish to paint the component instead of a custom draw method.

Note: There's no return type for constructors.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
3

Your Ball class seems to look ok. It doesn't need to extend anything. You will need to pass the Graphics object from the paintComponent of your game object to the Ball draw method.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
1

Your class is fine but I recommend extending a class. This class usually called as Sprite or Action or GameObject contains the basic information like

image (or animation), position, collision rect and some basic functions like get and set it's position, speed and some collision detection functions if you wish.

Some resources.

Hope they help. And to draw the object, do

g.drawImage(ball.image, ball.x, ball.y, null);
Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91