Java2D: Is it always safe to cast Graphics into Graphics2D

馋奶兔 提交于 2019-11-27 14:34:30
Jorge Ferreira

According to the discussion here, it is always safe to cast from Graphics to Graphics2D. However I am not able to quickly find the official Sun statement on this.

The reason it is valid to cast from Graphics to Graphics2D, is because Sun have said that all Graphics objects returned by the API in Java 1.2 or above will be a subclass of Graphics2D.

Another hint here with the same conclusion.

Graphics Object can always be cast Graphics2D g2d = (Graphics2D)g;

In the book Filthy Rich Client by Chet Haase and Romain Guy they are saying that Swing almost always uses a Graphics2D object. Exceptions from this are printing and Swing's DebugGraphics object. So as long as none of these situations apply to your code it is safe to cast to Graphics2D.
Both of the authors worked at Sun, so I would assume that they know what they are talking about.

The 2D Graphics Trail says:

To employ Java 2D API features in the application, cast the Graphics object passed into a component’s rendering method to a Graphics2D object. For example:

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

This is the most "official" source I could find. Coming straight from Sun's Java Tutorials, I'd say that this is the officially sanctioned way of doing it. I wouldn't have exactly minded if the JavaDocs spelled this out, though...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!