keylistener作为对象的子类不起作用

vjhs03f7  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(320)

基本上我想做的是,我有一个对象,叫做mainball。mainball有一个keydecater类作为其内部类,keydecater被添加到构造函数的mainball中。mainball是在游戏中创建的,但是mainball不响应击键。

public Mainball(){
    super(150,150,SIZE,SIZE);
    c=  Color.RED;
    addKeyListener(new KeyDetecter());
}
class KeyDetecter extends KeyAdapter{

    public KeyDetecter(){
    }

    double velocityfactor = 0.8;

    public void keyPressed(KeyEvent e){
        if(e.getKeyChar() == 'a'){
            x_velocity = -velocityfactor;
        }
        if(e.getKeyChar() == 'd'){
            x_velocity = velocityfactor;
        }
        if(e.getKeyChar() == 's'){
            ball.y_velocity = velocityfactor;
        }
        if(e.getKeyChar() == 'w'){
            y_velocity = -velocityfactor;
        }
        if(e.getKeyCode() == '1'){
            Shoot_Type = the_Game.SHOOT_ARROW;
        }
        if(e.getKeyCode() == '2'){
            Shoot_Type = the_Game.SHOOT_PARTICLE;
        }
    }

游戏也要求关注这里的窗口

if(button.getText().equals("Game")){
            try {
                game.walls = (ArrayList<wall>) SaveNLoad.load("wall_info.txt");
            } catch (Exception e1) {
                game.walls = new ArrayList<wall>();
            }
            frame.remove(current_panel);
            frame.add(game);
            game.ball.requestFocusInWindow(); /* ball is an mainball instance */
            current_panel = game;
            game.ball.x_center = 100;
            game.ball.y_center = 40;
            game.ball.y_velocity = 0;
        }
bfrts1fy

bfrts1fy1#

KeyEvent 这个 getKeyChar() 方法状态:
按键按下和按键释放事件不用于报告字符输入。因此,此方法返回的值保证仅对键类型的事件有意义。
因此,在上面的例子中,我认为如果将密钥处理的整个代码放在 KeyAdapter's keyTyped(KeyEvent e) 方法。

c2e8gylq

c2e8gylq2#

好吧,我给你做了测试,效果很好。

public static void main(String[] args) {
        JFrame t = new JFrame();
        t.setSize(500, 500);
        t.addKeyListener(new KL());
        t.setVisible(true);
    }

public static class KL extends KeyAdapter{

    public void keyPressed(KeyEvent e){
        if(e.getKeyChar() == 'a') System.out.println("a pressed");
    }
}

相关问题