Java2D:将 Graphics 转换为 Graphics2D 总是安全的
假设我们始终使用 Sun JVM(例如 1.5+),将 Graphics 引用强制转换为 Graphics2D 是否总是安全的?
我还没有看到它引起任何问题,据我了解,Graphics 类是遗留代码,但 Java 设计者不想更改 Swing 和 AWT 类的接口以保持向后兼容性。
Assuming we always use a Sun JVM (say, 1.5+), is it always safe to cast a Graphics reference to Graphics2D?
I haven't seen it cause any problems yet and, to my understanding, the Graphics class is legacy code but the Java designers didn't want to change the interfaces for Swing and AWT classes in order to preserver backwards compatibility.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据此处的讨论,从
图形
到Graphics2D
。 但是我无法快速找到 Sun 对此的官方声明。另一个提示此处具有相同的结论。
According to the discussion here, it is always safe to cast from
Graphics
toGraphics2D
. However I am not able to quickly find the official Sun statement on this.Another hint here with the same conclusion.
在 Chet Haase 和 Romain Guy 所著的 Filthy Rich Client 一书中,他们说 Swing 几乎总是使用
Graphics2D对象。 打印和 Swing 的 DebugGraphics 对象除外。 因此,只要这些情况都不适用于您的代码,就可以安全地转换为
Graphics2D
。两位作者都曾在 Sun 工作过,所以我认为他们知道自己在说什么。
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'sDebugGraphics
object. So as long as none of these situations apply to your code it is safe to cast toGraphics2D
.Both of the authors worked at Sun, so I would assume that they know what they are talking about.
2D Graphics Trail 说:
这是我能找到的最“官方”的来源。 直接来自 Sun 的 Java 教程,我想说这是官方认可的做法。 不过,如果 JavaDocs 详细说明了这一点,我也不会介意......
The 2D Graphics Trail says:
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...