在游戏中切换JPanel时,KeyListener不起作用

时间:2019-05-01 20:55:52

标签: java jframe jpanel actionlistener keylistener

我正在开发一个游戏,当我从MenuPanel切换到实际的游戏(Player)时,KeyListener将无法工作,角色也不会移动。我在两个类中都实现了KeyListener。我该如何解决这个问题?这是该游戏(播放器)的代码段:

public class Player extends JPanel implements ActionListener, KeyListener {


         private MijnProject mainVenster;

         public Player(MijnProject mainVenster) {

        this.mainVenster = mainVenster;
        addKeyListener(this);
        setFocusable(true); 
        requestFocusInWindow();
        Timer t = new Timer();
        t.scheduleAtFixedRate(new UpdateTimerTask() , 0, PERIOD);
     }

         public void keyPressed(KeyEvent e) {

        int code = e.getKeyCode();
        if(code==KeyEvent.VK_UP) {
            up();
        }

        if(code==KeyEvent.VK_DOWN) {
            down();
        }
        if(code==KeyEvent.VK_RIGHT) {
            right();
        }
        if(code==KeyEvent.VK_LEFT) {
            left();
        }
        if(code==KeyEvent.VK_SPACE) {
            bullet();   

        }


这是菜单(MenuPanel)的代码的一部分:

public class MenuPanel extends JPanel implements ActionListener, KeyListener
{

    private JButton playKnop, highScoreKnop, quitKnop;
    private MijnProject mainVenster;

    public MenuPanel(MijnProject mainVenster) 

    {   addKeyListener(this);
        setFocusable(true); 
        this.mainVenster = mainVenster;

                playKnop = new JButton("Play");     
        playKnop.addActionListener(this);

        quitKnop = new JButton("Quit");
        quitKnop.addActionListener(this);

        highScoreKnop = new JButton("High Scores");
        highScoreKnop.addActionListener(this);

        this.add(playKnop);
        this.add(quitKnop);
        this.add(highScoreKnop);

    }


    public void actionPerformed(ActionEvent ae)
    {
        if (ae.getSource() == playKnop)
        {
            mainVenster.switchPanel(new Player(mainVenster));
        }

    }


    public void keyPressed(KeyEvent arg0) {

    }


    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {

    }

}

0 个答案:

没有答案