需要恢复图形原始状态当被覆盖的油漆或的paintComponent [英] The Need To Restore Graphics Original State When Overwritten paint or paintComponent

查看:235
本文介绍了需要恢复图形原始状态当被覆盖的油漆或的paintComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道大多数的Java code,以覆盖油漆或paintComponent方法,大多没有恢复旧态图形对象后,他们不得不改变状态的图形对象。例如,setStroke,setRenderingHint ...

I realize most of the Java code to overwritten paint or paintComponent, most of them doesn't restore the old state of graphics object, after they had change the state of graphics object. For example, setStroke, setRenderingHint...

我不知道它是否是我们恢复回来显卡的老态对象,从方法返回前一个很好的做法。例如:

I was wondering whether it is a good practice that we restore back the old state of graphics object, before returning from the method. For example

public void paintComponent(Graphics g) {
    super.paintComponet(g);
    Stroke oldStroke = g.getStroke();
    g.setStroke(newStroke);
    // Do drawing operation.
    g.setStroke(oldStroke);
}

这是一个好的做法呢?或者是在做什么?

Is this a good practice? Or it is over done?

推荐答案

您不应改变图形在所有传入的对象,而在它的一个副本,然后您再进行处置执行所有图形操作。再也没有必要在所有然后复位状态。

You should not alter the Graphics object passed in at all, rather perform all your graphics operations on a copy of it which you then dispose. There'll be no need to reset the state at all then.

public void paintComponent(Graphics g1) {
    super.paintComponent(g1);
    final Graphics2D g = (Graphics2D)g1.create();
    try {
         // ...Whole lotta drawing code...
    } finally {
         g.dispose();
    }
}

这篇关于需要恢复图形原始状态当被覆盖的油漆或的paintComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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