Java KeyListener切换JPanel后未响应 [英] Java KeyListener not responding after switching JPanels

查看:167
本文介绍了Java KeyListener切换JPanel后未响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在JPanels之间切换时,KeyListener没有响应(由于未获得焦点)而出现问题.

I got a problem with the KeyListener not responding(due to not gaining focus) when I switch between JPanels.

我有Google,并且知道要解决此问题,我需要使用KeyBindings,但我不喜欢KeyBindings.所以我想知道,还有其他方法吗?

I have Google'd this and know that to fix this problem I need to use KeyBindings, but I don't like KeyBindings. So I was wondering, is there any other way?

这是JPanel的初始化代码,它的KeyListener没有响应:

Here is the init code of the JPanel that has an unresponsive KeyListener:

    public void init()
{
    setFocusable(true);
    requestFocusInWindow();
    requestFocus();
    addMouseListener(new MouseInput());
    addMouseMotionListener(new MouseInput());
    addMouseWheelListener(new MouseInput());
    addKeyListener(new KeyInput(p));

    t = new Timer(10, this);
    t.start();
}

如有需要,随时询问更多代码示例!

Feel free to ask for more code samples if you need to!

推荐答案

有问题的解决方案是在JPanel上调用requestFocusInWindow()以确保其将焦点放在KeyListener/KeyAdapter上,仅应调用添加Componnet之后(尽管为了确保我的组件具有焦点,我在通过revalidate()repaint()刷新JFrame之后调用了它)例如:

The hacky solution is to call requestFocusInWindow() on the JPanel to make sure it has focus for KeyListener/KeyAdapter this should only be called after the Componnet has been added (though to be sure my component has focus I called it after the JFrame is refreshed via revalidate() and repaint()) for example:

public class MyUI {

    //will switch to the gamepanel by removing all components from the frame and adding GamePanel
    public void switchToGamePanel() {
        frame.getContentPane().removeAll();

        GamePanel gp = new GamePanel();//keylistener/keyadapter was added to Jpanel here

        frame.add(gp);//add component. we could call requestFocusInWindow() after this but to be 98%  sure it works lets call after refreshing JFrame

        //refresh JFrame
        frame.pack();
        frame.revalidate();
        frame.repaint();

        gp.requestFocusInWindow();
    }

}
class GamePanel extends JPanel { 

      public GamePanel() {
          //initiate Jpanel and Keylistener/adapter
      }

}

但是您应该使用Swing KeyBinding(+ 1到@Reimeus注释).

However you should use Swing KeyBindings (+1 to @Reimeus comment).

请在此处阅读以熟悉它们:

Have a read here to get familiar with them:

现在,您已经阅读了让我们展示另一个示例来帮助阐明(尽管Oracle做得很好)

Now that you have read that lets show another example to help clarify (though Oracle did a good job)

如果我们想将KeyBinding添加到某个JComponent,即JButton for Esc ,则可以执行以下操作:

If we wanted to add a KeyBinding to a certain JComponent i.e JButton for Esc you would do:

void addKeyBinding(JComponent jc) {
        jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "esc pressed");
        jc.getActionMap().put("esc pressed", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.out.println("Esc pressed");
            }
        });

        jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), "esc released");
        jc.getActionMap().put("esc released", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.out.println("Esc released");
            }
        });
}

上面的方法将被称为:

JButton b=..;//create an instance of component which is swing

addKeyBinding(b);//add keybinding to the component

请注意:

1)您不需要同时使用KeyBindings,我只是演示了如何获取不同的键状态并使用Keybindings适当地执行操作.

1) You would not need both KeyBindings, I just showed how to get different key state and act appropriately using Keybindings.

2)此方法将添加一个Keybinding,只要按下 Esc 且组件位于具有焦点的窗口中,就会激活该Keybinding,您可以通过指定另一个即:

2) This method will add a Keybinding which will be activated as long as Esc is pressed and the component is in the window which has focus, you can change this by specifying another InputMap i.e:

jc.getInputMap(JComponent.WHEN_FOCUSED).put(..);//will only activated when component has focus

这篇关于Java KeyListener切换JPanel后未响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆