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?
Basically, when you override a method, you can be equally or less specific.
Think about this:
A reference to a
JPanelis expected to be able to accept a Graphics reference as a parameter to thepaintComponentmethod. Your method, however, violates that requirement as it will not accept aGraphicsinstance, but only aGraphics2D.More information about this can be found https://stackoverflow.com/a/9950538/567864