Reputation: 331
In my program I am using Swing windows for my GUI, and I know that I'm supposed to use repaint and paintComponent methods to render swing components. I also have several custom class objects that need to be rendered inside the main window. For the sake of understanding, my program is a game that will have moving objects that need to be rendered 60 times per second.
In a game development tutorial I watched, the guy used a Jframe with Canvas, but he didn't use the paintComponent method. He simply made his own render() methods to draw all the graphics using graphics context he obtained from creating a bufferStrategy.
So if that works (which it does), why does everyone say to use the paintComponent methods and what exactly is the difference between them?
If I were to use the paintComponent way of doing things, how would I use bufferStrategy with that?
Upvotes: 0
Views: 1843
Reputation: 347184
In a game development tutorial I watched, the guy used a Jframe with Canvas, but he didn't use the paintComponent method. He simply made his own render() methods to draw all the graphics using graphics context he obtained from creating a bufferStrategy.
Canvas
is an AWT component, using a BufferStrategy
, you take over the painting process and become responsible for update the Graphics
context and scheduling it's push to the hardware/screen.
This is commonly known as "active painting", as you are constantly (one would assume at a constant frame rate), updating the buffer.
Swing uses a passive paint process, so you never know when a paint process might occur. Swing has it's own mechanisms for determining what should be repainted and when. Using repaint
, you make a request to these mechanisms that your component be repainted, but there is no guarantee that a paint cycle will be initiated because of it.
If you use any Swing component for you painting, you MUST use repaint
and paintComponent
, as the Swing is responsible for providing the context onto which you can paint.
If you want to use Canvas
, then you can use a BufferStrategy
instead.
Essentially, they are different approaches to painting. Remember though, if you use a BufferStrategy
, you lose ALL of the Swing API, you CAN NOT use Swing components with this approach, as they are not designed to work this way...
Upvotes: 3