0

Can someone please explain to me the difference or benefits rather to using the rectangle class

ex. Rectangle r1 = new Rectangle(x,y,w,h); 

versus the graphics class drawRec method?

g.drawRec(x,y,w,h);

I'm thinking that you can create a new object outside of paint() or paintcomponent() which gives creating an object more options and maybe the associated methods is a bonus? I'm just speculating though because the tutorial I was going through switched from using one to the other without explaining why. I believe I understand how to use them just not when it's better to use which. Please try to keep your responses at the beginner level seeing as how I'm just starting out but of course any assistance is GREATLY appreciated. Thanks!!

Here is a code segment of what I'm working with:

public void paintComponent(Graphics g){ 
 g.drawImage(yellowBall, xCoor, yCoor, this);
 Rectangle r1 = new Rectangle((boardXSize/2), (boardYSize/2),50, 50);
 g.setColor(Color.red);
 g.fillRect(r1.x, r1.y,r1.width, r1.height);
 repaint();
}
Tulains Córdova
39.6k13 gold badges102 silver badges157 bronze badges
asked Jun 18, 2014 at 12:46

2 Answers 2

0

You use instances of Rectangle when you have to manage them for some reason (e.g. in a drawing program or some kind of window or layout management). There is hardly a good reason to create them solely for calling Graphics.fillRect, as in your example.

answered Jun 18, 2014 at 14:57
1
  • ok awesome. Thanks for clarifying. I was thinking that but wasn't sure because the tutorial didn't explicitly state it. Thanks again for your help Commented Jun 18, 2014 at 23:20
0

The simplest thing to do is look at the JavaDocs for Rectangle. If you want any of these abilities, use a Rectangle.

Also, as @user281377 notes, a single Rectangle object is easier to manage, store in a List, persist, etc. than four ints.

answered Jun 18, 2014 at 15:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.