I am trying to code a little brick breaker project and I am having a trouble with the graphic aspects of it. I don't understand how to update properly my Panel. When I call the repaint() method it won't update every time. My "fix" was to add a call to repaint() in the paintComponent() method of my panel but it does not seems right and my panel will redraw multiple times. This is my code:
I have my play() method which will make the game work :
public void play()
{
long framesDrawn = 0;
long lastFrame = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
while(!hasGameEnded())
{
double dt = (currentTime - lastFrame)/1000.;
if(dt > 1./_fps) // Draws a new frame at the desired fps
{
framesDrawn++;
System.out.println(dt);
moveItems(dt);
drawNewFrame();
System.out.println("new frame drawn (frame "+framesDrawn+" )\n");
lastFrame = currentTime;
}
currentTime = System.currentTimeMillis();
}
}
It calls the drawNewFrame() method:
private void drawNewFrame()
{
ArrayList<GameItem> allItems = new ArrayList<>();
allItems.addAll(_allItems);
allItems.addAll(_platforms);
_gameFrame.getGamePanel().updateItems(allItems);
_gameFrame.getGamePanel().repaint();
_gameFrame.repaint();
}
And my custom JFrame and JPanel are:
public class GameFrame extends JFrame {
private GamePanel _gamePanel;
public GameFrame(GamePanel gamePanel)
{
_gamePanel = gamePanel;
this.setTitle("Brickbreaker");
this.setSize(800, 1200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.setContentPane(_gamePanel);
this.setVisible(true);
}
public GamePanel getGamePanel()
{
return _gamePanel;
}
}
public class GamePanel extends JComponent {
private int _gameWidth, _gameHeight;
private ArrayList<GameItem> _gameItems;
public GamePanel(int gameWidth, int gameHeight, ArrayList<GameItem> gameItems )
{
_gameWidth = gameWidth;
_gameHeight = gameHeight;
_gameItems = gameItems;
this.setOpaque(true);
this.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int x = getX();
int y = getY();
int height = getHeight();
int width = getWidth();
float widthRatioMultiplier = ( (float)width )/( (float)_gameWidth );
float heightRatioMultiplier = ( (float) height)/( (float) _gameHeight);
for( GameItem gameItem : _gameItems)
{
gameItem.draw(g, widthRatioMultiplier, heightRatioMultiplier );
}
repaint();
}
public void updateItems(ArrayList<GameItem> updatedItems)
{
_gameItems = updatedItems;
}
}