简体   繁体   English

paintComponent()的最佳实践

[英]best practice for paintComponent()

I am rendering a rectangle using Graphics library of java, in it paintComponent() method draws the rectangle and everything is fine in drawing regards. 我正在使用Java的Graphics库渲染矩形,在其中paintComponent()方法绘制了矩形,并且在绘制方面一切都很好。

My question is does the paintComponent keeps on rendering or it just renders once and if a window change or any event occurs it changes the view. 我的问题是paintComponent继续渲染还是仅渲染一次,如果窗口发生更改或发生任何事件,它将更改视图。 So I have written a simple System.out.println to check whether it keeps on printing it, and it does. 因此,我编写了一个简单的System.out.println来检查它是否继续打印,并且确实如此。 So is there a way to stop that from happening or is it fine to leave rendering as it is, since it is completing my objective? 那么,有什么方法可以阻止这种情况的发生?还是可以保留渲染,因为它已经完成了我的目标?

Start by taking a look at Painting in AWT and Swing and Performing Custom Painting 首先看一下AWT和Swing中的 绘画以及执行自定义绘画

Swing uses a passive rendering engine, that is, it only paints when it feels that it has to. Swing使用被动渲染引擎,即,仅在需要时才进行绘画。 Painting can happen for any number of reasons, many of which you don't control, but you can make a request to the repaint manager via the repaint method. 绘画的发生可能有多种原因,其中许多是您无法控制的,但是您可以通过repaint方法向重画管理器发出请求。

So I have written a simple System.out.println to check whether it keeps on printing it, and it does 所以我写了一个简单的System.out.println来检查它是否继续打印,并且确实

Would suggest that something is wrong, paintComponent shouldn't, under normal circumstances, be repeatedly called. 提示存在问题,在正常情况下, paintComponent不应重复调用。 This can, of course, happen if you are doing animation and need to update the graphics. 当然,如果您正在制作动画并且需要更新图形,则可能会发生这种情况。

So is there a way to stop that from happening or is it fine to leave rendering as it is 因此,有什么方法可以阻止这种情况的发生,还是可以将渲染保持原样

Consider providing a runnable example which demonstrates your problem. 考虑提供一个可运行的示例来演示您的问题。 This will result in less confusion and better responses. 这将减少混乱并改善响应。

Without some idea of what you are doing, there's no way to know what to suggest... 如果不知道自己在做什么,就无法知道建议...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM