Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

swing - KeyAdapter is not responding ~ Java

I'm creating a simple breakout game. However, the KeyAdapter isn't receiving the input. The code looks fine to me but maybe I'm missing something more basic?

public DatGamePanel(BustOut bo, long framerate) {

    setBackground(Color.black);
    setPreferredSize( new Dimension(GAME_WIDTH,GAME_HEIGHT));
    setFocusable(true);

    font = new Font("Sans Serif", Font.BOLD, 24);
    fm = this.getFontMetrics(font);

    this.bo = bo;
    period = 1000/framerate;
    bat = new Bat("bat.png",GAME_WIDTH,GAME_HEIGHT-32,2);

    //Get keyboard input :D
    addKeyListener( new KeyAdapter() {
        public void keyPressed(KeyEvent ke) {
            handleInputPressed(ke);
        }

        public void keyReleased(KeyEvent ke) {
            handleInputReleased(ke);
        }
    });
}

public void handleInputPressed(KeyEvent ke) {
    int a = ke.getKeyCode();
    switch(a) {
        case KeyEvent.VK_LEFT:
        bat.keyHandle(0);
        test = 1;
        break;

        case KeyEvent.VK_RIGHT:
        bat.keyHandle(2);
        break;
    }
}

public void handleInputReleased(KeyEvent ke) {
    System.out.println("Key Pressed");
    int a = ke.getKeyCode();
    switch(a) {
        case KeyEvent.VK_LEFT:
        bat.keyHandle(1);
        test = 0;
        break;

        case KeyEvent.VK_RIGHT:
        bat.keyHandle(3);
        break;
    }       
}

These are all the basic input handles. The test variable doesn't change when I push the Left arrow. What's wrong here...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're just listening for a few keys and your component doing the listening may not have the focus, you're far better of using key bindings than a KeyListener. Please look here How to use Key Bindings

If this recommendation doesn't seem to help, consider creating and posting an SSCCE (please click on the link), a small compilable, runnable program that demonstrates your best attempt at solving this. Then we can inspect your code, run it, modify it and best be able to help you fix it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...