简体   繁体   中英

Why wont my Java program acknowledge any key strokes using KeyListener?

I have literally no idea why my program isn't recognizing keyboard input. I have places print statements throughout the program to determine the issue, and I have determined that the keyPressed method never activates. This is for a game which I am making for a class project, and yes I am a relatively beginner programmer. Thanks in advance! (Code below)

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.ImageIcon;
import javax.swing.JApplet;


public class Dodger extends JApplet implements Runnable, KeyListener {

Thread myThread;

public Image bg;
public Image pic;
public boolean loaded;

public int cx, cy, speed, x, y;

public void init(){
    setSize(800,800);
    loaded = false;
    x = 2;
    y = 400;
    cx = 0;
    cy = 0;
    speed = 3;
    myThread = new Thread(this);
    myThread.start();
    addKeyListener(this);
}

public void run(){
    loadpic();
    repaint();
    while (myThread!=null)
    {

        try{
            myThread.sleep(18);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        repaint();
    }
}

public void upMotion(){
    cy = cy + speed;
}

public void downMotion(){
    cy = cy - speed;    
}

public void leftMotion(){
    cx = cx - speed;
}

public void rightMotion(){
    cx = cx + speed;
}

@Override
public void keyPressed(KeyEvent k) {

    if (k.getKeyCode() == KeyEvent.VK_LEFT) {
        System.out.println("work");
        leftMotion();
    }

    if (k.getKeyCode() == KeyEvent.VK_RIGHT) {
        rightMotion();
    }

    if (k.getKeyCode() == KeyEvent.VK_UP) {
        upMotion();
    }

    if (k.getKeyCode() == KeyEvent.VK_DOWN) {
        downMotion();
    }
}

@Override
public void keyReleased(KeyEvent e) {
}

@Override
public void keyTyped(KeyEvent e) {
}

public void loadpic(){
    bg = new ImageIcon(getClass().getResource("back.png")).getImage();
    pic = new ImageIcon(getClass().getResource("smile.png")).getImage();
    loaded = true;
    repaint();
}



public void paint(Graphics g){
    g.drawImage(bg, 0, 0, this);
    g.drawImage(pic, cx, cy, this);
}   
}

The key events are detected just fine when the applet is focusable & has focus. Managing focus has always been a problem with applets. The problem is mostly that Sun never bothered to specify the focus behavior that should ideally apply to a mixed page of focusable HTML elements and applet(s).

As per Tom's advice, add to the end of init()

setFocusable(true);

To be safe, also override:

public void start() {
    this.requestFocusInWindow();
}

As an aside, generally it is better to use key bindings in Swing. They also require the applet to have input focus.


First off, you probably want to separate out your class from your KeyListener, as it makes it a bit harder to read.

Next, you want to get rid of the bare Thread and wrap it in a timer.

import javax.swing.Timer;

class Dodger extends JApplet {

    Timer imageUpdater; //replaces Thread

    /*...*/
    public void init() {
        /*etc*/
        loadpic();
        int repaintInterval = 100;
        imageUpdater = new Timer(repaintInterval,
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    repaint();
                }
            }
        );
        imageUpdater.start();
        addKeyListener(new KeyHandler());
        setFocusable(true);
     }

    /*...*/
    private class KeyHandler extends KeyAdapter {
        /* Note that with this implementation, you do not have to override
         * unnecessary methods, as KeyAdapter is an abstract class that
         * implements all of the methods of KeyListener.
         */
        @Override
        public void keyPressed(KeyEvent e) {
        /*...*/
        }
    }
    /*...*/
}

Most of this is just code cleanup - the actual problem may be fixed (according to Tom, see comments) with the setFocusable(true) .

I'm not really sure if it applies to Applets, but your Thread may not allowing the event dispatching to occur.

Try to run your "work" with SwingWorker .

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