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

1

7

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);
   }
}
Padlock answered 18/12, 2015 at 15:24 Comment(2)
This is going to be mostly a subjective matter, but I'd say that the examples you give are perfectly fine. If you were to implement your own Point and Rectangle classes, chances are they would be almost identical to the ones AWT uses - and if that's the case, why bother?Hotien
it is hard to anwer yes/no on your question. if you are doing swing application, and your code will be nothing more than swing app, then i would say, yes it is ok to use java.awt.Rectangle class.. but if you are planning to do something else with it, you need to keep in mind fact wven if you use your code for android app, you will stilll need to provide swing/awt jar files. and adding complex libary to the project only for one class or even one method it is overkillBiauriculate
R
6

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.

Radioactivate answered 18/12, 2015 at 15:43 Comment(1)
Alright great thanks! That sounds reasonable. I did think it was kind of counter-intutive if I couldn't use stuff like Rectangle or Point.Padlock

© 2022 - 2024 — McMap. All rights reserved.