3

我完全不知道如何KeyListener在小程序中使用(好吧,我有一个好主意)。我知道这与将焦点放在小程序上有关,但我不知道如何做到这一点。我的程序作为应用程序运行良好,但它不会将键盘输入作为小程序接收。如果有人可以给我一些帮助,那就太棒了。

我的代码是:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Window extends JApplet {

    static Ship ship;
    static ColorPanel panel;
    static boolean up=false, down=false, left=false, right=false;

            public static class PanelListener implements KeyListener{

        public void keyPressed(KeyEvent e){
            switch(e.getKeyCode()) {
                    case 38: ship.setMoving(true); down = true;break;
                    case 40: ship.setMoving(true); up = true;break;
                    case 37: ship.setMoving(true); left = true;break;
                    case 39: ship.setMoving(true); right = true;break;
                    case 32: ship.setFiring(true); break;
                    case 49: ship.setSwitching(true); ship.switchOrdinance(49); break;
                    case 50: ship.setSwitching(true); ship.switchOrdinance(50); break;
                    case 51: ship.setSwitching(true); ship.switchOrdinance(51); break;
                    case 52: ship.setSwitching(true); ship.switchOrdinance(52); break;
                    case 83: if(ship.shieldState()){ship.shieldOff();}else{ship.shieldOn();}
            }
            ship.setDirection(up,down,left,right);
            ship.setVelocity(3);
        }
        public void keyReleased(KeyEvent e){
            switch(e.getKeyCode()) {
                case 38: ship.setMoving(false); down = false; break;
                case 40: ship.setMoving(false); up = false; break;
                case 37: ship.setMoving(false); left = false; break;
                case 39: ship.setMoving(false); right = false; break;
                case 32: ship.setFiring(false); break;
                case 49: ship.setSwitching(false); break;
                case 50: ship.setSwitching(false); break;
                case 51: ship.setSwitching(false); break;
                case 52: ship.setSwitching(false); break;
                default: ship.setMoving(false); ship.setFiring(false); ship.setSwitching(false); left=false; right=false; up=false; down=false;
            }
            ship.setDirection(up,down,left,right);
            if(!up || !down || !right || !left){
                ship.setVelocity(0);
            }
        }
        public void keyTyped(KeyEvent e){
        }
    }

        public void init(){
            Container pane;
            ship=new Ship();
            panel = new ColorPanel(Color.black, 1340, 640);
            panel.sendShip(ship);
            pane=getContentPane();
            pane.add(panel);
            addKeyListener(new PanelListener());
        }
}
4

1 回答 1

2

您是对的,您需要在init方法结束时将其设置为可聚焦

setFocusable(true);

如果您不这样做,您至少必须在面板中单击以获取遇到的键。

于 2013-01-31T16:38:29.763 回答