Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use swing and awt classes for my non-graphics related classes in my programs?

So, lets say I have some game, take Pong for example. Obviously, you generally speaking don't want to mix game-logic into graphics classes, so the class for Ball or Paddle is sepearte from the JPanel which actually draws them. Ball has the movement logic for the ball, its current location, hit detection, etc. However, is it bad practice for me to use graphics classes from Swing and awt in my Ball class? For example, if I were to use a java.awt.Rectangle to determine the hitbox. Even though I am not drawing it in this class, I am using it. Or if I were to use Java.awt.Point to store coordinates.

By the way, the reason I am asking is because I have been told many times on this site not to mix graphics with other parts.

Using Rectangle in non-graphics class: (Is this bad practice?)

public class Ball {
    static Rectangle hitbox = new Rectangle(0,10,20,20);
    static void checkHit() {
        if(hitbox.intersects(Paddle.hitbox) //do something
    }

}

My Graphics class:

public class DrawMyStuff extends JPanel {
   void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(Color.BLACK);
        Graphics2D g2d = (Graphics2D) g;
        g2d.draw(Ball.hitbox);
   }
}
like image 609
Ashwin Gupta Avatar asked Dec 18 '15 15:12

Ashwin Gupta


1 Answers

I'd say that for most part, you shouldn't do this.

Exceptions from the rule

There are however a (small) set of helper classes inside that package that are actually only data holders of a "nice" type. Why invent wheels when you already got them? These would be "okay to use" in my world.

  • Dimension
  • Insets
  • Point
  • Rectangle (and all other Shapes like Polygon, Area and so on)

These can be used to describe graphical problems while they are not directly coupled to on-screen-resources.

like image 83
Jan Avatar answered Oct 13 '22 13:10

Jan