Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

}
share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

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.

share|improve this answer
    
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 –  cjayem13 Jun 18 at 23:20
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.