I'm currently working on my first game using Java. I have a red square (the player) in a grid of stone blocks. The game is looking like this: https://i.stack.imgur.com/P6qSE.png
After I accomplished this, I moved on to trying out the KeyListener
. I also have a Player
class with a few variables and a paint
funcition. Here is the Player
class:
import java.awt.Color;
import java.awt.Graphics;
public class Player {
int width, height;
int x = 300;
int y = 300;
public Player() {
width = 25;
height = 25;
}
public void drawPlayer(Graphics g) {
g.setColor(Color.red);
g.fillRect(x, y, width, height);
}
}
And here is the KeyListener
:
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
player.y += 25;
repaint();
} else if(e.getKeyCode() == KeyEvent.VK_A) {
player.x -= 25;
repaint();
} else if(e.getKeyCode() == KeyEvent.VK_S) {
player.y -= 25;
repaint();
} else if(e.getKeyCode() == KeyEvent.VK_D) {
player.x += 25;
repaint();
}
System.out.println(player.x + ", " + player.y);
}
As you can see at the bottom of the keyPressed
function, I added: System.out.println(player.x + ", " + player.y);
to make sure the KeyListener
was working well (it is).
Now, since everything is working, last step was repainting the JPanel to update the players position. This is that code:
@Override
public void paint(Graphics g) {
super.paint(g);
stone.drawStone(g);
player.drawPlayer(g);
g.setColor(Color.gray);
for (int j = 0; j < Display.WIDTH; j += tileSize) {
for (int i = 0; i < Display.HEIGHT; i += tileSize) {
g.drawRect(i, j, tileSize, tileSize);
}
}
}
In theory, my player should update position (since I already did repaint()
in the KeyListener
), but it doesn't. My player doesn't move. What could this be? I'm guessing it has something to do with repainting the JPanel but I don't know how to fix this.
Do you have any suggestions? Thanks in advance.
Side note: I have 4 main classes, Player, Game (here is where 95% of the code came from), Display (JFrame), and Main (draws JFrame and starts gameloop (but im not currently using a gameloop)).