获取Graphics2D? [英] Getting the Graphics2D?

查看:109
本文介绍了获取Graphics2D?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D)g; //

    double r = 100; //the radius of the circle

    //draw the circle

    Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 2 * r, 2 * r);
    g2.draw(circle);

这是我程序中类的一部分,我的问题在于

This is part of a class within my program, my question lies in the

Graphics2D g2 = (Graphics2D)g;

为什么必须在(Graphics2D)后面加上"g",以及括号中的"Graphics2D"到底是什么意思,我是从书本中学到的,而这些都没有得到完整的解释.

Why must you include the "g" after the (Graphics2D), and what exactly does the "Graphics2D" Within the parenthesis mean, i am learning out of a book and neither of these were ever fully explained.

推荐答案

您正在将 Graphics2D 强制转换为 Graphics 上下文 g .在 继承铸造部分.

You are casting Graphics2D to the Graphics context g. Read more about casting here in Inheritance in the Casting section.

这最终要做的是分配给传递给 paintComponent 方法的 Graphics 上下文使用 Graphics2D 的可用方法.取消强制转换后,您将只能使用 Graphics

What this ultimately does is allot you use the available methods of Graphics2D with the Graphics context of the passed to the paintComponent method. Whitout the casting, you'd only be limited to the methods of the Graphics class

Graphics2D Graphics 的子类,因此通过使用 Graphics2D ,您可以同时获取 Graphics 的所有方法 Graphics2D 类中方法的优点.

Graphics2D is a subclass of Graphics so by using Graphics2D you gain all the methods of Graphics while taking advantage of the methods in the Graphics2D class.

附带说明

  • 您不应覆盖 paint .同样,如果您愿意,则不应在 JApplet 之类的顶级容器上绘画.

  • You shouldn't be override paint. Also if you are, you shouldn't be painting on top level containers like JApplet.

代替在 JPanel JComponent 上绘画,并覆盖 paintComponent 而不是 paint 并调用 super.paintComponent .然后只需将 JPanel 添加到父容器中.

Instead paint on a JPanel or JComponent and override paintComponent instead of paint and call super.paintComponent. Then just add the JPanel to the parent container.

public DrawPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
    }
}

有关更多信息,请参见 自定义绘画 Graphics2D

See more at Custom Painting and Graphics2D

这篇关于获取Graphics2D?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆