Home > Back-end >  Java KeyListener doesn't do anything. also doesn't give an error
Java KeyListener doesn't do anything. also doesn't give an error

Time:10-31

I've seen that there are many questions here regarding this topic, but I think that they are all different to my problem. I want to create a simple game. I want to move the blue square around when w,a,s or d is pressed. The following code doesn't throw any error so I have no idea why it's not working.

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main implements KeyListener{

    static JLabel ufo;
    
    public static void main(String[] args) {
        
        JFrame frame = new JFrame();
        frame.setSize(1080, 720);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(true);
        frame.setLayout(null);
        
        JPanel panel = new JPanel();
        panel.setSize(1080, 720);
        panel.setLayout(null);
        panel.setBackground(Color.darkGray);
    
        ufo = new JLabel();
        ufo.setBounds(0,0,100,100);
        ufo.setBackground(Color.blue);
        ufo.setOpaque(true);
        
        panel.add(ufo);
        
        frame.add(panel);
        
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);     
    }

    @Override
    public void keyTyped(KeyEvent e) {
        
          switch(e.getKeyChar()) {
           case 'a': ufo.setLocation(ufo.getX()-10, ufo.getY());
            break;
           case 'w': ufo.setLocation(ufo.getX(), ufo.getY()-10);
            break;
           case 's': ufo.setLocation(ufo.getX(), ufo.getY() 10);
            break;
           case 'd': ufo.setLocation(ufo.getX() 10, ufo.getY());
            break;
          }
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {   
    }   
}

CodePudding user response:

The only thing needed is an instance of Main passed to frame as a key listener.

public static void main(String[] args) {
    [...]
    frame.setVisible(true);     
    frame.addKeyListener(new Main());
}
  • Related