Difference between Graphics and Graphics2D?
Asked Answered
C

1

12

What is difference between Graphics and Graphics2D?
Whether Graphics2D is extend of Graphics?

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawRect(25, 25, 20, 20); //use Graphics to paint rectangle
    Graphics2D g2 =(Graphics2D)g;
    g2.drawRect(0, 0, 20, 20); // use Graphics2D to paint rectangle
}
Conscious answered 13/10, 2013 at 11:52 Comment(1)
It is practically the Graphics class with methods of AffineTransform class.Hiroshima
H
19

Graphics itself is an abstract class, therefore you cant create its instance. It only defines some interface and some functionality, so it can be extended by other class.

So even this Graphics g, which is used as parameter in paintComponent, is not only Graphics. The standard java library has only two extended class : DebugGraphics, Graphics2D, so the Graphics g you are using is Graphics2D instance stored in Graphics g.

If it is not, the line Graphics2D g2 =(Graphics2D)g; would end with an error.

Harbinger answered 13/10, 2013 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.