I've been looking for a explicit answer for this but I can't find one anywhere.
A Graphics object is always passed into the java paint
methods examples:
paintComponent(Graphics c)
paintIcon(Component c, Graphics g, int x, int y)
Often these paint
methods are overriden by subclassses and changes need to be applied to the Graphics
object, examples: setColor()
or fillRect()
. These changes can either be applied to the passed in Graphics
object, or a new one can be created using g.create()
.
I read in another SO answer that you should call g.create()
anytime you are making any changes that are "not easily undone", but the article was not clear on which changes are "not easily undone" (I also can no longer find this article for reference).
I know that transposing or translating are situations where you should create a new graphics object. But what about simpler actions like g.setColor(...)
or g.fillRect(...)
?
My Question:
- When should you call
g.create()
to use for yourGraphics
object and what situations should you use the one passed into the method? - Is there any downside to creating a new
Graphics
object?
Example To try to narrow this question down, I'll give an example. For the following situation, would I need to create a new graphics object?
private Icon delegate;
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
delegate.paintIcon(c, g, x, y);
g.setColor(Color.gray);
int width = getIconWidth() - 4;
int height = getIconHeight() - 4;
g.fillRect(x + 2, y + 2, width, height);
}