代码适用于java图形,但不适用于graphics2d

时间:2009-02-23 00:59:37

标签: java graphics java-2d

在paintcomponent中。它以g为参数,g可以是graphics或graphics2d。该类扩展了jpanel。然后:

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

如果g是图形工作,但如果它是graphics2d则不然。它与两者编译,但graphics2d不会改变背景颜色。怎么来的?

1 个答案:

答案 0 :(得分:4)

JPanelJComponent的子类)只有paintComponent(Graphics)方法。它没有带签名paintComponent(Graphics2D)的方法。

覆盖paintComponent(Graphics)方法可以通过以下方式完成:

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

但是,定义带有paintComponent(Graphics2D)签名的方法(如下所示)是合法的,但它永远不会被称为,因为它不会覆盖任何定义的方法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.
}

Java API specifications for the JComponent classJPanel的超类)有一个方法摘要,列出了属于该类的所有方法。

有关在Swing中绘画的更多信息;