【问题标题】:What is use of super.paint(g)?super.paint(g) 有什么用?
【发布时间】:2014-06-19 11:50:14
【问题描述】:

谁能解释一下super.paint(g) 的用途,其中g 是Applets 或awt 或swings 或Java 中的Graphics 变量。

我研究了一下,发现是用来override的,但是这个override有什么用呢?

我是初学者。如果可能的话,你能用小号example 解释paint(g)super.paint(g) 之间的区别吗?或者请帮我处理这段代码?

/*
Let us consider this code 
This has only one paint declaration i.e; subclass's paint method declaration, no     declaration for superclass's paint function... when we explicitly call superclass's paint function 
what is the use of super.paint(g) and is it going to use superclass's paint declaration??
*/

import java.awt.*;
import java.applet.*;
/*
<applet code="superpaintDemo" height=768 width=1366>
</applet>
*/
class superpaintDemo extends Applet
{

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawString("This is Demo",200,200);
    }
}

【问题讨论】:

  • 你说的是来自 awt/swing 的油漆吗?我不明白你想了解什么... super 它曾经从父级调用 smthing ,而 paint(g) 到 ... paint (: 看看这里oracle.com/technetwork/java/painting-140037.html 和文档
  • 我不会继续修复你的帖子。请查看the help center,了解如何创建好帖子。
  • 你能告诉我哪里出错了......格式化时?感谢您的帮助

标签: java applet awt paint super


【解决方案1】:

public void paint(Graphics g)

绘制容器。这会将绘制转发到作为该容器子级的任何轻量级组件。 如果重新实现此方法,则应调用super.paint(g) 以便正确呈现轻量级组件。如果一个子组件被 g 中的当前剪切设置完全剪切,paint() 将不会转发给该子组件。

直接来自the docs

【讨论】:

    【解决方案2】:
    1. 首先,我在自己的绘制方法中添加了 super.paint(g)。

    当它重新绘制时,之前绘制的东西会被清除。

    抱歉,我不能发布超过 2 个链接。

    1. 然后,我在自己的绘制方法中删除 super.paint(g)。

      remove super.paint(g)

    您可以看到之前在面板上绘制的东西仍然存在。

    当你添加super.paint(g)时,在你的方法中它会调用这个子类的超类中的方法。我的类RussiaPanel扩展了JPanel,而JPanel扩展了JComponent。它会调用JComponet中的“public void paint(Graphic g)”方法,Panel上的东西会被清空。更多细节可以参考API文档。

    希望对你有所帮助,并原谅我英语不好。

    【讨论】:

      【解决方案3】:

      我猜它的用法就像你使用的其他一些方法super.method()。 这用于调用超类中的方法。基本上取决于 根据您的目的,您决定如何使用它。大多数情况下,我们 覆盖组件子类中的paint(Graphics g) 以实现 我们的意图。如果你调用super.paint(g),它可能会调用 这个子类的超类。

      如果你想让超类首先(或最后)绘制,你应该调用super.paintComponent(g)

      在 Swing 中调用 super.paint(g) 会导致讨厌的递归。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-17
        • 2015-04-27
        • 2012-05-07
        • 1970-01-01
        • 2010-09-15
        相关资源
        最近更新 更多