Search code examples
javaswingapiawtpaintcomponent

Why can't paintComponent accept a Graphics2D object?


public class MyDrawPanel extends JPanel {
    public void paintComponent(Graphics g){

        Graphics2D gd2 = (Graphics2D) g;
        GradientPaint gradient = new GradientPaint(70,70,Color.blue,150,150,Color.red);


    }
}

Why is this valid but not this:

public class MyDrawPanel extends JPanel {
    public void paintComponent(Graphics2D g){

        GradientPaint gradient = new GradientPaint(70,70,Color.blue,150,150,Color.red);

        g.setPaint(gradient);
        g.fillOval(70,70,100,100);
    }
}

First one renders, but the second one renders no graphics other than the frame. I noticed that paintComponent() requires a Graphics object, but if Graphics2D is a subclass of the Graphics object why can I not call a subclass of Graphics?

Is there some concept I am not picking up as to why this is?


Solution

  • Basically, when you override a method, you can be equally or less specific.

    Think about this:

    JPanel p = new MyPanel();
    p.paintComponent(someGraphicsInstance);
    

    A reference to a JPanel is expected to be able to accept a Graphics reference as a parameter to the paintComponent method. Your method, however, violates that requirement as it will not accept a Graphics instance, but only a Graphics2D.

    More information about this can be found https://stackoverflow.com/a/9950538/567864