处理 AWT 图形上下文的最佳方法是什么?
我们的 Swing 应用程序的一些用户报告显示屏上出现奇怪的现象。 范围从组件在一两秒内无法正确重新绘制,一直到应用程序的整个部分被重新绘制,就像窗口区域上的平铺壁纸一样。
该应用程序由各个级别的开发人员(从经验丰富的 Java 人员到刚从大学毕业的年轻人)花费五年左右的时间开发而成,正如您所期望的,一些 AWT 代码完全是一团糟。 我现在面临的任务是在接下来的几个月左右的时间里尽可能多地纠正错误。
其中一些很容易处理。 仅在事件调度线程、异步 IO 之类的事情上处理组件,我希望将消息传达给团队的其他成员。
我想知道的是处理 Graphics 上下文的最佳方法,尤其是在 PaintComponent() 上下文中。 我看到很多...
public void paintComponent( Graphics g ) {
super.paintComponent( g );
Graphics2D gfx = (Graphics2D)g;
// ...Whole lotta drawing code...
}
这样做更好吗?
public void paintComponent( Graphics g ) {
super.paintComponent( g );
Graphics2D gfx = (Graphics2D)g.create();
// ...Whole lotta drawing code...
gfx.dispose();
}
如果 g 参数要在其他绘画中重用,那么我不需要将其恢复到良好状态,撤消 AffineTransforms 等吗?
Some users of our Swing application have reported weird artefacts appearing on the display. This ranges from components not repainting themselves properly for a second or two, right upto whole portions of the application being repainted like tiled wallpaper over areas of the window.
The app has been worked on by developers of all levels between experienced Java guys to young chaps right out of university over the course of five years or so, and as you'd expect, some of the AWT code is an outright mess. I'm now faced with the task of trying to correct as much of the badness as I can over the next few months or so.
Some of this is easy to deal with. Deal with components only on the event dispatch thread, IO asynchronously, kind of thing, and I'm hopefully getting the message across to the rest of the team.
What I'd like to know is the best way of dealing with Graphics contexts, especially in a paintComponent() context. I see a lot of...
public void paintComponent( Graphics g ) {
super.paintComponent( g );
Graphics2D gfx = (Graphics2D)g;
// ...Whole lotta drawing code...
}
Is it better practice to do this?
public void paintComponent( Graphics g ) {
super.paintComponent( g );
Graphics2D gfx = (Graphics2D)g.create();
// ...Whole lotta drawing code...
gfx.dispose();
}
If the g parameter is going to be reused in other paints then don't I need to restore it to a good state, undo AffineTransforms, etc.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Filthy Rich Clients 的说法,您不应该更改传递给您的 Graphics 对象(在我看来,这作为 API 很糟糕)。
处理它的正确方法稍微冗长一些:
IIRC,在 Sun 实现中,如果您不处理“子图形”对象,那并不重要。 (不要引用我的话。)
您可能希望将该注释位委托给另一个对象。
According to Filthy Rich Clients, you should not alter the
Graphics
object passed to you (which sucks as an API, IMO).The correct way to handle it is slightly more verbose:
IIRC, in the Sun implementation it doesn't matter if you don't dispose of "sub-Graphics" objects. (Don't quote me on that.)
You might want to delegate that comment bit to another object.
听说jdk-1.6.12中已经修复了这个问题,但没有尝试。
I heard that this has been fixed in jdk-1.6.12, but didn't try it.