Ofri Adiv
Ofri Adiv

Reputation: 41

keyPressed method not working Java

Hi I am new to Java and I am trying to move a JPanel (Player) across a JFrame using the arrow keys but for some reason it is not working. I believe it is because the keyPressed method is not responding when a key is pressed but I don't really know.

This is the code for the Player class:

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class Player extends JPanel implements KeyListener{
    int x=0,y=0;
    public Player(){
        this.setBounds(x, y, 9, 9);
        this.setOpaque(true);
        this.setBackground(Color.red);
        this.setFocusable(true);
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_UP){
            this.setBounds(x, x-9, 9, 9);
        }else if(key == KeyEvent.VK_DOWN){
            this.setBounds(x, y+9, 9, 9);
        }else if(key == KeyEvent.VK_RIGHT){
            this.setBounds(x+9, y, 9, 9);
        }else if(key == KeyEvent.VK_LEFT){
            this.setBounds(x-9, y, 9, 9);
        }

    }
    public void keyReleased(KeyEvent arg0) {}

    public void keyTyped(KeyEvent arg0) {}


}

Thanks in advance!

Edit: This is the code for the JFrame: import javax.swing.JFrame;

public class Cave {


    public static void main(String[] args) {
        JFrame frame = new JFrame("Cave Generator");
        frame.setBounds(0, 0, 0, 0);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

            Player p = new Player();
        frame.getContentPane().add(p);

    }

}

Upvotes: 4

Views: 1778

Answers (1)

Vivek Singh
Vivek Singh

Reputation: 2073

There are two issues with your code.

  1. The first issue is that once you call the visible call on your frame than you are adding the player component on the frame.
  2. You are not storing the last location of the player.

Make the below changes in your code and it should run:

Cave

public class Cave {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Cave Generator");
        frame.setBounds(0, 0, 0, 0);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Player p = new Player();
        frame.getContentPane().add(p);
        frame.setVisible(true);
    }

}

Player#keyPressed

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_UP){
        y = y-9;
    }else if(key == KeyEvent.VK_DOWN){
        y = y+9;
    }else if(key == KeyEvent.VK_RIGHT){
        x = x+9;
    }else if(key == KeyEvent.VK_LEFT){
        x = x-9;
    }
    this.setBounds(x, y, 9, 9);
}

Upvotes: 4

Related Questions