paintComponent(g) 还是 paintComponent(g2)?

4
public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.fillRect(0,0,25,25);
}

或者

public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.fillRect(0,0,25,25);
}

如果我使用Graphics2D,哪种是正确的? 我仍然需要在paintComponent(g)中绘制或将其传递给g2吗?
抱歉如果这是一个愚蠢的问题,我会使用第二个选项,但我想知道哪种方式是正确的,以防我做错了什么。

2
如果g确实是一个Graphics2D(我不认为AWT会回来),那么这些字面上是相同的。 - Elliott Frisch
没有任何区别,它是同一个对象。 - user207421
2个回答

4

方法paintComponent接受Graphics作为参数,而Graphics2DGraphics的子类。因此,将g传递给super.paintComponent相当于传递g2。但如果super.paintComponent被重载,其中一个版本接受Graphics,另一个版本接受Graphics2D(这里不是这种情况),则会有所不同。


4

Graphics是一个抽象类,因此不能实例化。鉴于本地Java库中只有两个Graphics2DDebugGraphics实现,您可以假定g将是Graphics2D,这使得第二种方法相当冗余(但不是不正确)。DebugGraphics很少用于手工绘图。

总之,您可以以任何方式传递它,因为它们完全等价。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接