Search code examples
javatextgraphicsinstanceantialiasing

Why does this work? (Java, Graphics object)


Here's my code:

public void paint(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    g.drawString("This is my string", 200, 200);
}

This works correctly; the text comes out as anti-aliased. However, why does it work? The text is drawn by the g object, however as far as I can see, the anti-aliasing was turned on for the g2 object. How does the g object get it?


Solution

  • Graphics2D g2 = (Graphics2D) g;
    

    Both g and g2 are references to the same object (g). g refers to the object as Graphics2D whereas g2 refers to the object as Graphics2D.