# converting a class to 2D?

Discussion in 'Java' started by Ian Stanley, Jul 29, 2003.

1. ### Ian StanleyGuest

Hi,
I have a program which adds shapes (rectangles, circles, etc) to a vector v.
this is done by:
v.add(new Rects(x, y, w, h)) ;
Is there a easier way to make the Rects class have all the charateristics of
a 2D Rectangle?(such as methods like contains etc) while keeping the
inheritance structure
effectively the same as v.add(new 2DRects(x, y, w, h)) ;
Any pointers appreciated
regards
Ian

the present way a rectangle is created is:
class shape extends JComponent {
int x, y ;
int w, h ;

shape(int x, int y, int w, int h) {
super() ;
this.x = x ;
this.y = y ;
this.w = w ;
this.h = h ;
}

class Rects extends shape {
Rects(int x, int y, int w, int h) {
super(x, y, w, h) ;
}

public void paint(Graphics g) {
g.drawRect(x, y, w, h) ;
}
}

Ian Stanley, Jul 29, 2003

2. ### Steve W. JacksonGuest

In article <>,
"Ian Stanley" <> wrote:

:> Hi,
:> I have a program which adds shapes (rectangles, circles, etc) to a vector v.
:> this is done by:
:> v.add(new Rects(x, y, w, h)) ;
:> Is there a easier way to make the Rects class have all the charateristics of
:> a 2D Rectangle?(such as methods like contains etc) while keeping the
:> inheritance structure
:> effectively the same as v.add(new 2DRects(x, y, w, h)) ;
:> Any pointers appreciated
:> regards
:> Ian
:>
:> the present way a rectangle is created is:
:> class shape extends JComponent {
:> int x, y ;
:> int w, h ;
:>
:> shape(int x, int y, int w, int h) {
:> super() ;
:> this.x = x ;
:> this.y = y ;
:> this.w = w ;
:> this.h = h ;
:> }
:>
:> class Rects extends shape {
:> Rects(int x, int y, int w, int h) {
:> super(x, y, w, h) ;
:> }
:>
:> public void paint(Graphics g) {
:> g.drawRect(x, y, w, h) ;
:> }
:> }

I suspect you're unaware of the Shape interface already in existence in
the java.awt package. It's implemented by a series of predefined
classes, including RectangularShape (superclass of both Rectangle and
Rectangle2D).

And don't forget that you add Objects to a Vector. When you retrieve
them, you can always determine what actual Class each is an instance of
on the fly. By virtue of being instances of that particular class, they
automatically provide the relevant methods.

And then, you can decide whether your shapes really need to be
self-drawing components as you're apparently trying to do by having them
extend JComponent. If they do, then your Shape class above (following
the proper convention and always naming a class so that it begins with
an uppercase letter) should probably be renamed for clarity and then
implement that interface. That, of course, will be much more work than
simply using existing Shape implementors and having them draw into
something like a JPanel.

= Steve =
--
Steve W. Jackson
Montgomery, Alabama

Steve W. Jackson, Jul 29, 2003