在一个游戏里用了 paintImmediately 来刷新某 JComponent cc 为 opaque,空布局,没有子控件用 System.currentTimeMillis() 取时间差测得 c 的 paintComponent() 方法耗时为 0 msc.paintImmediatly 的每次调用却耗时 15 ~ 16 ms 不等,这正常吗?
我测量的方法正确吗?
有没有什么办法改进 paintImmediatly 的效率?如果不用 paintImmediatly,有什么办法可以安全的得到一个往屏幕上绘制 c 的 Graphics 对象?swing游戏jcomponent
repaint是不行的,因为它不是同步调用,对EDT的时间占用不可控,而且最终repaint所导致的每一次重绘对EDT的占用时间更长,实测多于15~16毫秒。paintImmediately 是同步调用,内部好像对绘制区域有优化,同时实现了双缓冲。如果实在不行,再考虑绕开painImmediately,见楼顶最后一个问题。
其实我是想问,直接 c.getGraphics() 然后绘制是不是安全,因为我大概看了一下 painImmediately 里面调用的 safelyGetGraphics 方法,没看懂,不知道它跟直接 c.getGraphics() 有什么区别。
public Graphics getGraphics()
Returns this component's graphics context, which lets you draw on a component. Use this method to get a Graphics object and then invoke operations on that object to draw on the component. Overrides:
getGraphics in class Component
Returns:
this components graphics context这个方法没有抛异常。
问题本身也许问的有问题,
总之是没有得到想要的答案……感谢楼上三位的关注,结贴了分数平分了吧