I am coding a Pacman game and I ran into few problems while trying to implement it.
I have a main JFrame
which holds the background, and the points on it, the points are added in the paint()
method.
I added to the frame a JPanel
that makes the board which Pacman is on, Pacman is being painted by paintComponent()
.
Pacman movement is decided by a `KeyListener which is on the frame.
The problems I'm running into:
If upon pressing a key I call the
paint
function of the frame, which later calls thepaintComponent
method of the panel, my screen is blinking because each time it repaints all of the points.If upon pressing a key I call directly to the panel
paintComponent()
method and paint the Pacman, it stays on the board like in gif number 2.
1:
2:
This is the paint
method of the frame:
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < 800; i++)
for (int j = 0; j < 800; j++)
if (boardPanel.getBoard().getTileXY(i, j).getPill() != null)
g.drawImage(yellowPil, i, j, null);
boardPanel.paintComponent(g);
}
And this is the paintComponent
:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(pacmanImage,pacman.getX(),pacman.getY(),null);
}
this is how i call each of this methods (its in the jframe class) :
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_RIGHT:
boardPanel.movePacman(Direction.RIGHT);
boardPanel.paintComponent(getGraphics()); // this will casue `
problem 2`
break;
case KeyEvent.VK_LEFT:
boardPanel.movePacman(Direction.LEFT);
repaint(); // this will cause problem 1
break;
case KeyEvent.VK_DOWN:
boardPanel.movePacman(Direction.DOWN);
repaint();
break;
case KeyEvent.VK_UP:
boardPanel.movePacman(Direction.UP);
repaint();
break;
}
}