简体   繁体   中英

Java - graphics paint

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?

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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM