Roo*_*kie 0 java swing timer keylistener jpanel
当我在JPanel之间切换时,我遇到了KeyListener没有响应(由于没有获得焦点)的问题.
我有谷歌这个,并知道要解决这个问题,我需要使用KeyBindings,但我不喜欢KeyBindings.所以我想知道,还有其他方法吗?
这是JPanel的初始化代码,它具有无响应的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();
}
Run Code Online (Sandbox Code Playgroud)
如果需要,请随时索取更多代码示例!
在哈克解决方法是调用requestFocusInWindow()上JPanel,以确保它集中了KeyListener/ KeyAdapter现在增加了Componnet后这应该只能被称为(但可以肯定我的组件具有焦点我把它称为后JFrame通过刷新revalidate()和repaint()),例如:
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
}
}
Run Code Online (Sandbox Code Playgroud)
但是你应该使用Swing KeyBindings(+1到@Reimeus评论).
在这里阅读以熟悉它们:
现在你已经阅读了,让我们展示另一个例子来帮助澄清(尽管Oracle做得很好)
如果我们想要一个添加KeyBinding到某个JComponent即JButton对Esc你会怎么做:
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");
}
});
}
Run Code Online (Sandbox Code Playgroud)
上面的方法将被称为:
JButton b=..;//create an instance of component which is swing
addKeyBinding(b);//add keybinding to the component
Run Code Online (Sandbox Code Playgroud)
请注意:
1)你不需要两者KeyBindings,我只是展示了如何获得不同的关键状态并采取适当的行动Keybindings.
2)此方法将添加一个Keybinding只要Esc按下并且组件在具有焦点的窗口中就会被激活的方法,您可以通过指定另一个来改变它,InputMap即:
jc.getInputMap(JComponent.WHEN_FOCUSED).put(..);//will only activated when component has focus
Run Code Online (Sandbox Code Playgroud)