gpt4 book ai didi

java - 获取 Graphics2D?

转载 作者:行者123 更新时间:2023-11-29 07:50:18 26 4
gpt4 key购买 nike

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);

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

Graphics2D g2 = (Graphics2D)g;

为什么必须在 (Graphics2D) 之后加上“g”,以及括号内的“Graphics2D”到底是什么意思,我正在从一本书中学习,但这些都没有得到充分解释。

最佳答案

您正在将 Graphics2D 转换为 Graphics 上下文 g。在 Inheritance 中阅读有关类型转换的更多信息在 Casting 部分。

这最终所做的是分配您使用 Graphics2D 的可用方法以及传递给 paintComponent 方法的 Graphics 上下文。如果没有转换,您将仅限于 Graphics 类的方法

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


边注

  • 你不应该覆盖paint。此外,如果您是,则不应在像 JApplet 这样的顶级容器上绘制。

  • 而是在 JPanelJComponent 上绘制并覆盖 paintComponent 而不是 paint 并调用 super.paintComponent。然后只需将 JPanel 添加到父容器即可。

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

查看更多信息 Custom PaintingGraphics2D

关于java - 获取 Graphics2D?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21710323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com