Java2D:将 Graphics 转换为 Graphics2D 总是安全的

发布于 2024-07-07 01:34:13 字数 157 浏览 7 评论 0原文

假设我们始终使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

假装爱人 2024-07-14 01:34:13

根据此处的讨论,图形Graphics2D。 但是我无法快速找到 Sun 对此的官方声明。

有效投射的原因
Graphics到Graphics2D,是因为Sun
已经说过所有 Graphics 对象
由 Java 1.2 中的 API 返回或
上面将是一个子类
Graphics2D。

另一个提示此处具有相同的结论。

图形对象始终可以转换
Graphics2D g2d = (Graphics2D)g;

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;

兮颜 2024-07-14 01:34:13

在 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'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.

汐鸠 2024-07-14 01:34:13

2D Graphics Trail 说:

要在应用程序中使用 Java 2D API 功能,请将传递到组件渲染方法的 Graphics 对象转换为 Graphics2D 对象。 例如:

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

这是我能找到的最“官方”的来源。 直接来自 Sun 的 Java 教程,我想说这是官方认可的做法。 不过,如果 JavaDocs 详细说明了这一点,我也不会介意......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文