Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java KeyListener doesn't do anything. also doesn't give an error

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) {   
    }   
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading