Search code examples
javakeykeylistenerkeyevent

unable to take keyboard inputs in java using KeyListener


i am trying to take keyboard inputs to change the boolean's value but keylisteners are not working
those bolleans values will be used later in other class
heres the method i am having issues with

public boolean upPressed, downPressed, leftPressed, rightPressed;

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if(code == KeyEvent.VK_W){
            upPressed = true;}
        
        else if(code == KeyEvent.VK_S){
            downPressed = true;}
        
        else if(code == KeyEvent.VK_A){
            leftPressed = true;}
        
        else if(code == KeyEvent.VK_D){
            rightPressed = true;}
        
    }

i am using a different class which extends JPanel, frame is in a different class and key listener is in a different class and i have this.setFocusable(true);this.addKeyListener(keyH);

and if u want, here's the full code : https://github.com/PROMAN8625/2dGAME


Solution

  • Your code snippet looks fine. Maybe you didn't add KeyListener to the frame.

    Here is a working example:

    import java.awt.FlowLayout;
    import java.awt.Frame;
    import java.awt.Label;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    public class KeyListenerExample implements KeyListener
    {
        public boolean upPressed, downPressed, leftPressed, rightPressed;
    
        @Override
        public void keyTyped(KeyEvent e) {
        }
    
        @Override
        public void keyPressed(KeyEvent e)
        {
            int code = e.getKeyCode();
            if (code == KeyEvent.VK_W) {
                upPressed = true;
            }
            else if(code == KeyEvent.VK_S){
                downPressed = true;}
    
            else if(code == KeyEvent.VK_A){
                leftPressed = true;}
    
            else if(code == KeyEvent.VK_D){
                rightPressed = true;}
    
            System.out.println("The key Pressed was: " + e.getKeyChar());
            System.out.println("upPressed: " + upPressed);
            System.out.println("downPressed: " + downPressed);
            System.out.println("leftPressed: " + leftPressed);
            System.out.println("rightPressed: " + rightPressed);
            System.out.println("\n");
    
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
        }
    
        public static void main(String[] args)
        {
            //Setting the Frame and Labels
            Frame f = new Frame("Demo");
            f.setLayout(new FlowLayout());
            f.setSize(500, 500);
            Label l = new Label();
            l.setText("This is a demonstration");
            f.add(l);
            f.setVisible(true);
    
            //Creating and adding the key listener
            KeyListenerExample k = new KeyListenerExample();
            f.addKeyListener(k);
        }
    }