0

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 your Graphics 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);
    } 
Community
  • 1
  • 1
mdewitt
  • 2,526
  • 19
  • 23
  • 1
    Kind of a broad question, but I'd create a new one if I needed to do an AffineTransform on my Graphics object or if I wanted to change the Stroke, Paint, Clip. – Hovercraft Full Of Eels Jan 28 '14 at 02:53
  • 1
    I (personally) think you've actually answered your own question. I personally look at from the point view of how much my changes might effect other components within the paint cycle. Things like, transformations and rendering hints are big ones – MadProgrammer Jan 28 '14 at 03:00

0 Answers0