views:

253

answers:

1

inside a paintcomponent. it takes g as parameter, and g can be graphics or graphics2d. the class extends jpanel. then:

super.paintComponent(g);
this.setBackground( Color.BLACK );

if g is graphics it works, but if it's graphics2d it doesn't. it compiles with both, but graphics2d doesn't change the background color. how come?

+4  A: 

JPanel (which is a subclass of JComponent) only has a paintComponent(Graphics) method. It does not have a method with the signature paintComponent(Graphics2D).

Overriding the paintComponent(Graphics) method can be accomplished by the following:

public void paintComponent(Graphics g)
{
    // Do things.
}

However, defining a method with the signature with paintComponent(Graphics2D) like the following is legal, but it won't ever be called, as it is not overriding any method that is defined in JComponent:

public void paintComponent(Graphics2D g)
{
    // Do things.
    // However, this method will never be called, as it is not overriding any
    // method of JComponent, but is a method of the class this is defined in.
}

The Java API specifications for the JComponent class (which is the superclass of JPanel) has a method summary which lists all the methods that are part of the class.

More information about painting in Swing;

coobird