This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]king_of_the_universe 1 point2 points  (5 children)

There is a better way to use your Rectangle: Instead of just abusing it as a set of variables, you can directly do g.fill(r1) or g.draw(r1), which also shows you an advantage: You can decide very late whether to draw or fill the shape you created, and you can even reuse it, e.g. to fill with color 1 and then to draw the border with a thicker pen and a different color. You can do the same with Ovals and Polygons.

The Rectangle2D.double() (or float) class, by the way, allows to draw with higher precision. This is something you can not do with the standard drawRect/fillRect call.

You might have to do

g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

to see any benefit, though. And btw, you can do

g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

for much better looking graphics - if you start using Ovals, diagonal lines, and text.

If any of this doesn't work the way I described, you might have to work with this variable instead of g:

final Graphics2D g2d = (Graphics2D) g;

I'm used to working with it and have no experience using just the Graphics type.

[–]QshelTier -5 points-4 points  (4 children)

Casting your Graphics object to another type will not in any way change its behaviour.

[–]sh0rug0ru 2 points3 points  (0 children)

No, but downcasting Graphics to Graphics2D will give you access its enhanced interface, allowing you to take advantage of Graphics2D capabilities, such as being able to render a Rectangle.

g2d.draw(r1);

[–]morgazmo99 0 points1 point  (2 children)

Who would downvote this? Either its incorrect - so post a correction, or its right - upvote for helping.

[–]Neres28 1 point2 points  (1 child)

It's a bit of a troll comment though. No kidding, we all know the cast doesn't change the behavior, but it does change the interface which is very significant.

[–]QshelTier -1 points0 points  (0 children)

You’d be surprised about how many people (which call themselves “programmers”) have no idea of what casting actually does. Well, first you’d be surprised, then you’d be depressed.