首页 > 解决方案 > 油漆组件中的 g 参数(图形 g)

问题描述

我是java的初学者。我在一本书中遇到方法paintComponent() ,书中说系统在需要调用该方法时调用该方法。

我的问题是 g 参数是什么?

它是Graphics类还是Graphics2D类的对象?

它是如何通过系统传递的?

是不是我们画完元件后有面板和图纸组成的?

我无法想象程序

非常感谢

标签: javaswinggraphicsjpanelpaintcomponent

解决方案


Graphics 参数是一个 Graphics2D 对象。在这种情况下,paint 方法采用了一个抽象的 Graphics 类。这个类不能被实例化。Java 会给它传递一个 Graphics2D 对象,当你需要使用 'g' 时,你需要将它强制转换为 Graphics2D 以确认它是一个 Graphics2D 实例。然后您可以将其用作 Graphics2D 对象,而不是用作实现抽象 Graphics 对象的实例。

因此,虽然 'g' 是一个 Graphics 对象,但为该方法传递了一个 Graphics2D 对象,并且需要强制转换才能使用它。

本教程很好地总结了它(http://www.bogotobogo.com/Java/tutorials/javagraphics3.php):

参数 g 是一个 Graphics 对象。实际上,g 引用的对象是 Graphics2D 类的一个实例。

因此,如果我们需要使用 Graphics2D 类中的方法,我们可以直接使用 paintComponent(Graphics g) 中的 g。然而,我们可以用一个新的 Graphics2D 变量来转换它

我想我找到了传递实际 Graphics2D 对象的位置。在 Component.java 类中,看起来在第 4356 行,一个 SunGraphics2D 对象被返回并传递给 JPanel,该 JPanel 调用了paintComponent。

public Graphics getDrawGraphics() {
    revalidate();
     Image backBuffer = getBackBuffer();
      if (backBuffer == null) {
          return getGraphics();
       }
       SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics();
       g.constrain(-insets.left, -insets.top,
                    backBuffer.getWidth(null) + insets.left,
                    backBuffer.getHeight(null) + insets.top);
       return g;
    }

我不确定这是否正是制作 Graphics2D 对象的地方,但它绝对是它被传递给 paintComponent 方法的地方之一。


推荐阅读