2
\$\begingroup\$

I'm making a game in java right now. I've looked around at various tutorials for making Java games and there doesn't seem to be a consistent way to access a Graphics object to draw stuff on the screen.

Three of the different ways have been

  1. Overriding the paintComponent() method in a class that extends JPanel
  2. Using the getGraphics() method to get the graphics object in a class that extends JPanel
  3. Creating a BufferStrategy object and using the getDrawGraphics() method to get the graphics object to draw

All three implementations seem to work, I'm just confused about the difference between them, and in which situations would you use each?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I recommend the third one for making games. Because in:

CASE-1 When you override the paintComponent method all the drawing code inside the method is invoked by calling repaint method. Which is not good, because the repaint method is a just request to Swing to draw stuff. Due to this you might not get consistent frames. You should use this case only if you do not really care about inconsistent frames, for example, the Snake Game.

CASE-2 This case is also not recommended. It is kind of similar to 1st one.

CASE-3 This case should be used if you want a consistent game frame rate and do not want flickering in your game. This method renders when it should render and does not delay like the 1st case. Most of the games using this render method.

I would recommend you to use the third case, because it is the best of the three. I have built many games using that approach.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .