java Java2D:将 Graphics 转换为 Graphics2D 总是安全的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/179415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java2D: Is it always safe to cast Graphics into Graphics2D
提问by Outlaw Programmer
Assuming we always use a Sun JVM (say, 1.5+), is it always safe to cast a Graphics reference to Graphics2D?
假设我们总是使用 Sun JVM(比如 1.5+),将 Graphics 引用转换为 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.
我还没有看到它引起任何问题,据我所知,Graphics 类是遗留代码,但 Java 设计人员不想更改 Swing 和 AWT 类的接口以保持向后兼容性。
采纳答案by Jorge Ferreira
According to the discussion here, it is always safe to cast from Graphicsto Graphics2D. However I am not able to quickly find the official Sun statement on this.
根据这里的讨论,从Graphicsto 转换总是安全的Graphics2D。但是,我无法快速找到 Sun 对此的官方声明。
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.
从 Graphics 转换为 Graphics2D 是有效的,因为 Sun 已经说过 Java 1.2 或更高版本的 API 返回的所有 Graphics 对象都将是 Graphics2D 的子类。
Another hint herewith the same conclusion.
此处的另一个提示具有相同的结论。
Graphics Object can always be cast Graphics2D g2d = (Graphics2D)g;
图形对象总是可以转换 Graphics2D g2d = (Graphics2D)g;
回答by Roland Schneider
In the book Filthy Rich Clientby Chet Haase and Romain Guy they are saying that Swing almost always uses a Graphics2Dobject. Exceptions from this are printing and Swing's DebugGraphicsobject. 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.
在Chet Haase 和 Romain Guy 的Filthy Rich Client一书中,他们说 Swing 几乎总是使用Graphics2D对象。打印和 Swing 的DebugGraphics对象除外。因此,只要这些情况都不适用于您的代码,就可以安全地将其转换为Graphics2D.
两位作者都在 Sun 工作,所以我假设他们知道他们在说什么。
回答by MathiasKegelmann
The 2D Graphics Trailsays:
在2D图形小道说:
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:
要在应用程序中使用 Java 2D API 功能,请将传递到组件渲染方法的 Graphics 对象转换为 Graphics2D 对象。例如:
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...
这是我能找到的最“官方”的来源。直接来自 Sun 的 Java 教程,我会说这是官方认可的做法。我不会完全介意JavaDocs是否说明了这一点,但是......

