简体   繁体   English

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

[英]code works for java graphics, but not graphics2d

inside a paintcomponent. 在paintcomponent里面。 it takes g as parameter, and g can be graphics or graphics2d. 它以g为参数,并且g可以是graphics或graphics2d。 the class extends jpanel. 该类扩展了jpanel。 then: 然后:

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

if g is graphics it works, but if it's graphics2d it doesn't. 如果g是图形,它可以工作,但是如果是graphics2d,则不能。 it compiles with both, but graphics2d doesn't change the background color. 它可以同时编译,但是graphics2d不会更改背景颜色。 how come? 怎么会?

JPanel (which is a subclass of JComponent ) only has a paintComponent(Graphics) method. JPanel (是JComponent的子类)仅具有paintComponent(Graphics)方法。 It does not have a method with the signature paintComponent(Graphics2D) . 它没有带有签名paintComponent(Graphics2D)

Overriding the paintComponent(Graphics) method can be accomplished by the following: 可以通过以下方法来覆盖paintComponent(Graphics)方法:

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 : 但是,使用如下所示的带有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.
}

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. JComponent (这是JPanel的超类)的Java API规范有一个方法摘要,该摘要列出了该类的所有方法。

More information about painting in Swing; 有关在Swing中绘画的更多信息;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM