简体   繁体   中英

JAVA: Program not detecting key presses using KeyListener

I'm making a space shooter game in Java. I have it set to move up when I press the up key, but it is currently not working at all. I am using the KeyPressed method in the KeyListener interface. Here is my code. It is in 2 classes.

Game.java

package main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class Game extends Canvas implements Runnable, KeyListener {

    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    public static final String TITLE = "Space Shooter";

    private boolean running = false;
    private Thread thread;

    private Player player;

    private BufferedImage playerImage;

    int playerx;
    int playery;

    public Game() {
        player = new Player((WIDTH/2)-32, 400); 
        try {
            playerImage = ImageIO.read(this.getClass().getResourceAsStream("/res/player.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        addKeyListener(this);
    }

    private synchronized void start() {
        if (running)
            return;

        running = true;
        thread = new Thread(this);
        thread.start();
    }

    private synchronized void stop() {
        if (!running)
            return;

        running = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(1);
    }

    @Override
    public void run() {     
        long lastTime = System.nanoTime();
        final double amountOfTicks = 60.0;
        double ns  = 1000000000 / amountOfTicks;
        double delta = 0;
        int updates = 0;
        int frames = 0;
        long timer = System.currentTimeMillis();
        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            if (delta > 1) {
                tick();
                updates++;
                delta--;
            }
            render();
            frames++;

            if (System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                System.out.println(updates + " TICKS, " + frames + " FPS");
                updates = 0;
                frames = 0;
            }
        }
        stop(); 
    }

    public void tick() {
        playerx = player.getX();
        playery = player.getY(); 
    }

    public void render() {
        BufferStrategy bs = this.getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(3);
            return;
        }
        Graphics g  = bs.getDrawGraphics();

        g.drawImage(playerImage, playerx, playery, this); 

        g.dispose();
        bs.show();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_UP) {
            player.setY(playery -= 5);
        }
    }

    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

    public static void main(String[] args) {

        Game game = new Game();
        JFrame frame = new JFrame(TITLE);

        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(game);
        frame.getContentPane().setBackground(Color.BLACK);
        frame.setVisible(true); 

        game.start();

    }

}

Player.java

package main;

public class Player {

    int x, y; 

    public Player(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

}

When you click on the game and then press the keys does it work? If so all you need to do is call

setFocusable(true);
requestFocus();

then it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM