Question

I'm trying to make a simple game in java where you can move the player (Defender) in the 4 directions. I tried to make the key detecting with a key adapter, but it doesn't work. What could be the problem (I tried to do a System.out.println at the key press to make sure that the problem isn't at the Defender)? Code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class DefenderComponent extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;

    private static final int WIDTH = 160;
    private static final int HEIGHT = 120;
    private static final int SCALE = 4;

    Defender player = new Defender();

    public DefenderComponent() {
        Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
        setMinimumSize(size);
        setMaximumSize(size);
        setPreferredSize(size);

        addKeyListener(new TKeyListener());

        Timer timer = new Timer(5, this);
                timer.start();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test2");
        frame.add(new DefenderComponent());
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        frame.setFocusable(true);

        new DefenderComponent();
    }


    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        Image i = player.getImage();
        g2d.drawImage(i, player.getX(), player.getY(), i.getWidth(this) * SCALE, i.getHeight(this) * SCALE, this);
    }

    public void actionPerformed(ActionEvent e) {
        player.move();
        repaint();  
    }
}
Was it helpful?

Solution

KeyEvents are only generated for the component that has focus. A JPanel is not focusable by default.

Don't use a KeyListener. Instead you should be using Key Bindings which are more flexible.

See Motion Using the Keyboard for more information and examples.

OTHER TIPS

frame.addActionListener(this);

is what you missed.

that line says. this class is an ActionListener. please call this class when you receive an action.

if you want to add the ActionListener to the JPanel

public DefenderComponent() {
    addActionListener(this);
    ....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top