【问题标题】:g argument in paintComponent(Graphics g)油漆组件中的 g 参数(图形 g)
【发布时间】:2018-08-01 14:42:52
【问题描述】:

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

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

Graphics类还是Graphics2D类的对象?

系统是如何传递的?

我们绘制组件后是否由面板和图纸组成?

我无法想象过程

非常感谢

【问题讨论】:

  • Graphic g 引用也可以接受Graphic2D 类的实例,因为该类是Graphic 的子类型。您可以通过打印g.getClass()的结果找出传递了哪个类的实例。
  • “我的问题是 g 参数是什么?” Java 文档很棒,请参阅 JComponent.paintComponent(Graphics)。话虽如此,传递给 Swing 绘制方法的 Graphics 实例通常可转换为 Graphics2D。只是,这保证。
  • @Andrew Thompson 如何将对超类实例的引用转换为子类实例?我知道这是不可能的
  • 什么意思?如果class Child extends Parent{..} 则使用代码void someMethod(Parent p){ Child ch = (Child) p} 是可能的并且将编译,因为它可以与Child 实例一起使用,例如someMethod(new Child());。如果您传递Parent 实例,它可能无法正常工作,但是您将得到运行时异常。
  • @Pshemo 好的,谢谢。因此,当系统将 Graphics2D 类型的参数传递给方法时,可以进行强制转换

标签: java swing graphics jpanel paintcomponent


【解决方案1】:

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

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

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

参数g是一个Graphics对象。实际上,引用的对象 by 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 方法的地方之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多