Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paintComponent(g) or paintComponent(g2)?

public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.fillRect(0,0,25,25);
}

OR

public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.fillRect(0,0,25,25);
}

Which would be correct if I was using Graphics2D? Would I still paintComponent(g) or pass that to g2 instead?

Sorry if this is a stupid question, I would use the second one but I just want to know which would be the correct way in case I'm doing something wrong.

like image 636
joey942 Avatar asked Feb 07 '23 08:02

joey942


2 Answers

Graphics is an abstract class, and as such cannot be instantiated. Given that Graphics has only two implementations in the native Java library, Graphics2D and DebugGraphics, you can assume that g will be Graphics2D, making the second method rather redundant (but not incorrect). DebugGraphics is rarely used to draw graphics by hand.

To summarize, you can pass it in either way, because they are 100% equivalent.

like image 191
AlterV Avatar answered Feb 08 '23 22:02

AlterV


The method paintComponent accepts Graphics as parameter, and Graphics2D is a sub-class of Graphics. So, passing g to super.paintComponent is equivalent to passing g2. It would be different, though, if super.paintComponent is overloaded so that one version accepts Graphics and another version accepts Graphics2D (which is not the case here).

like image 43
AhmadWabbi Avatar answered Feb 08 '23 23:02

AhmadWabbi