Can someone tell me what should I use for painting graphics on a JPanel
: Canvas
, or simply drawing everything in paintComponent()
? I am painting hundreds of small images around 30 times per second, and I wonder which one would be the most lightweight, and in what conditions should I use both? Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The issue is rather broad and the context rather slim.
Consider taking a look at Rotating multiple images causing flickering. Java Graphics2D and Swing animation running extremely slow for example.
The first uses
paintComponent
to render up to 10, 000 rotating images at 25fps (or as close as it can).The second actually animates up to 4, 500 component based images
The ability to paint effectively at this rate is only one consideration to the overall picture
Updated
The primary difference between using a
JPanel
andCanvas
is the difference in rendering algorithms.With a
JPanel
you are still at the mercy of the repaint manager. This approach is commonly known as "passive rendering". That is, the manager is responsible for determine what and when something should be painted. Paints are done ad-hoc, when the repaint manager decides something needs to be painted, such as because some OS event has requested that part or whole of the screen should be updated.Technically, you are not in control of this process and can only simply make requests that a repaint should occur. You may also incur some delays occasionally because the system has butted in and forced an update
Canvas
provides you with aBufferStrategy
, which is more closely tied to the underlying rendering pipeline, potentially, making it faster.With this, you become responsible for scheduling the repaints. This is commonly known as "active rendering".
You can still but heads with the OS with this approach...
Either way, unless your update/render pipelines are well optimised, you can still run into lots of problems and could actually get better performance from using
JPanel
instead ofCanvas
Personally, if you're not sure or if you've not done anything like this before, I'd start with
JPanel
. Generally, it's slightly simpler to deal with.I changed the linked example to maintain a FPS counter as well...