简体   繁体   中英

Using a keylistener to output a pressed key

I am following a tutorial online which reads key presses. It is quite an old video so I'm not sure if the syntax has changed. I've also looked at other questions on here and can't seem to find a solution.

My issue is that it is not printing a pressed key to the console. No error is being thrown to me

Game.Java:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;

public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 240840600533728354L;
    public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
    private Thread thread;
    private boolean running = false;
    private Random r;
    private Handler handler;


    public Game(){
         handler = new Handler();

         this.addKeyListener(new KeyInput());
         new Window(WIDTH, HEIGHT, "The Game", this);

         r = new Random();

         handler.addObject(new Player(WIDTH/2-32,HEIGHT/2-32,ID.Player));
         handler.addObject(new Player(WIDTH/2+64,HEIGHT/2-32,ID.Player2));
    }

    public synchronized void start() {
        thread = new Thread(this);
        thread.start();
        running = true;
    }

    public synchronized void stop() {
        try{
            thread.join();
            running = false;
        }catch(Exception e ) {
            e.printStackTrace();
        }
    }

    public void run() {
        long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 10000000; //amount of ticks
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;
        while(running){
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1){
                tick();
                delta--;
            }
            if(running)
                render();
                frames++;

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

        private void tick(){
            handler.tick();
        }

        private void render(){
            BufferStrategy bs = this.getBufferStrategy();
            if(bs == null){
                this.createBufferStrategy(3);
                return;
            }

            Graphics g = bs.getDrawGraphics();

            g.setColor(Color.black);
            g.fillRect(0, 0, WIDTH, HEIGHT);

            handler.render(g);

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


    public static void main(String args[]){
     new Game();   
    }
}

KeyInput.Java

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter  {

    private Handler handler;

    //public KeyInput(Handler handler){
    //  this.handler = handler;
    //}

    public void keyPressed(KeyEvent e){
        int key = e.getKeyCode();
        System.out.println(key);
    }

    public void keyReleased(KeyEvent e){
        int key = e.getKeyCode();
    }

}

Your thread terminates immediately after you start it, because of this:

 thread.start();
 running = true;

this causes your thread to terminate because when it is started the variable is not yet set to true

public void run() {
    ...
    while(running){ //here is the problem, this variable is stil false now

    }

Therfore change the order of the two statements and it should work:

public synchronized void start() {
    thread = new Thread(this);
    running = true;
    thread.start();
}

Edit : and be aware that you should do your rendering in the EventDispatchThread !

I tried adding focus and it worked, thanks to @user7291698

public Game(){
     setFocusable(true);
     requestFocus();
     requestFocusInWindow();
     handler = new Handler();

     this.addKeyListener(new KeyInput());
     new Window(WIDTH, HEIGHT, "The Game", this);

     r = new Random();

     handler.addObject(new Player(WIDTH/2-32,HEIGHT/2-32,ID.Player));
     handler.addObject(new Player(WIDTH/2+64,HEIGHT/2-32,ID.Player2));
}

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