添加KeyListener却按下keyEvent却不起作用是什么问题?

时间:2019-03-30 06:03:04

标签: java swing jpanel keylistener

我的侦听器已添加到JFrame / JPanel。问题是当我按下按钮时,什么也没发生。这里可能是什么问题?

以下是使用的代码:

public class GAMEGAMEHA extends JPanel{

    public static JFrame PacmanMainFrame = new JFrame();
    TheJGame newGame;

    GAMEGAMEHA() {
        setSize(new Dimension(1200, 700));
        JLabel BG = new JLabel();
        JButton start = new JButton();
        JButton howTo = new JButton();
        JButton credit = new JButton();
        JButton exit = new JButton();

        setLayout(null);

        start.setIcon(new ImageIcon(getClass().getResource("/data/SB.png")));

        start.setContentAreaFilled(false);
        start.addActionListener((ActionEvent e) -> {
            newGame = new TheJGame();
            GAMEGAMEHA.PacmanMainFrame.getContentPane().removeAll();
            System.out.println("Removed Components");
            GAMEGAMEHA.PacmanMainFrame.add(newGame);
            System.out.println("Added Game");
            GAMEGAMEHA.PacmanMainFrame.addKeyListener(newGame);
            System.out.println("Added KeyListeners");
            GAMEGAMEHA.PacmanMainFrame.setVisible(true);
            System.out.println("Set Visiblity to True");
        });

        start.setBorderPainted(false);
        add(start);
        start.setBounds(440, 140, 300, 70);

        howTo.setIcon(new ImageIcon(getClass().getResource("/data/HowToButton.jpg")));
        howTo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e
            ) {
                HowTo HowToScreen = new HowTo();
                GAMEGAMEHA.PacmanMainFrame.getContentPane().removeAll();
                GAMEGAMEHA.PacmanMainFrame.add(HowToScreen);
                GAMEGAMEHA.PacmanMainFrame.setVisible(true);
            }
        });
        howTo.setBorderPainted(false);
        add(howTo);

        howTo.setBounds(440, 220, 300, 70);

        credit.setIcon(new ImageIcon(getClass().getResource("/data/CreditsButton.jpg")));
        credit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e
            ) {
                Credit CreditScreen = new Credit();
                GAMEGAMEHA.PacmanMainFrame.getContentPane().removeAll();
                GAMEGAMEHA.PacmanMainFrame.add(CreditScreen);
                GAMEGAMEHA.PacmanMainFrame.setVisible(true);
            }
        });
        credit.setBorderPainted(false);
        add(credit);

        credit.setBounds(440, 300, 300, 70);

        exit.setIcon(new ImageIcon(getClass().getResource("/data/ExitButton.jpg")));
        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e
            ) {
                System.exit(JFrame.EXIT_ON_CLOSE);
            }
        }
        );
        exit.setBorderPainted(
                false);
        add(exit);

        exit.setBounds(
                440, 380, 300, 70);

        BG.setIcon(
                new ImageIcon(getClass().getResource("/data/MainMenu.jpg")));
        BG.setText(
                "BackgroundImage");
        add(BG);

        BG.setBounds(
                0, 0, 1200, 700);

    }

    public static void main(String[] args) {
        GAMEGAMEHA GameMENU = new GAMEGAMEHA();
        PacmanMainFrame.setSize(new Dimension(1200, 700));
        PacmanMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        PacmanMainFrame.setTitle("THE JUNGLE GAME: A Object-Oriented Programming Project");
        PacmanMainFrame.setResizable(false);
        PacmanMainFrame.setLocationRelativeTo(null);
        PacmanMainFrame.add(GameMENU);
        PacmanMainFrame.setVisible(true);
    }

}

这是游戏开始的时间: 问题在这里。主菜单很好,但是进入此处时,它既不接受也不读取任何键。

public class TheJGame extends JPanel implements KeyListener {

    BackgroundGame BG = new BackgroundGame();
    MainCharacter bens = new MainCharacter();
    static int MainCx = 22;
    static int MainCy = 20;
    static int BGx = 0;
    static int BGy = 545;

    TheJGame() {
        bens.initializeMChar();
        BG.initializeGGround();
        setBounds(0, 0, 1200, 700);
        setFocusable(true);

    }

    @Override
    public void paint(Graphics g) {

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 1200, 700);
        g.drawImage(BG.GGround, BGx, BGy, this);
        g.drawImage(BG.GGround, BGx + 1200, BGy, this);
        g.drawImage(bens.MCharacter, MainCx, MainCy, this);
        updateBG();
        updateFall();
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_SPACE) {
            MainCy+=5;
            repaint();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public void updateFall() {

        if (MainCy <= 445) {
            MainCy += 1;
            repaint();
        }

    }

    private void updateBG() {
        BGx -= 1;

        if (BGx == -1200) {
            BGx = 0;
        }

        repaint();

    }


}

2 个答案:

答案 0 :(得分:1)

主要问题

“主要”问题是,KeyListener对于监视Swing中的键盘输入不是一个很好的选择,它会遇到焦点问题,即注册的组件必须是可聚焦的并且具有键盘焦点,并且由于您在用户界面中添加了按钮,它们将使组件失去焦点。

一个更好的整体解决方案是使用Key Bindings API,它使您能够确定应在哪个焦点级别触发绑定

其他问题...

null布局非常难以管理和维护。有很多因素影响着组件在屏幕上的显示效果。您应尽可能避免使用null版式,并使用一个或多个版式管理器,这样可以节省很多时间

您已覆盖paint,但未兑现绘画链(未致电super.paint)。绘画是一个复杂的过程,由许多步骤组成。

通常,您应该覆盖paintComponent(并在进行任何自定义绘制之前调用super.paintComponent)。

请通读Painting in AWT and SwingPerforming Custom Painting,以获取有关在Swing中绘画的更多详细信息

答案 1 :(得分:0)

您没有将键侦听器添加到JPnael中,仅实现接口不足以将其添加到面板中。

addKeyListner(this);

将这行代码添加到您的构造函数中。