CardLayout中的Java键绑定
我有一个java程序,我对我的关键事件使用了KeyBinding。我也对我的JFrame使用了CardLayout 问题是,除非单击其他窗口并返回JFrame,否则KeyBindings不起作用。例如,我使用我的应用程序,使用Google Chrome,然后返回我的JFrame。然后键绑定工作 这是我的密码:CardLayout中的Java键绑定,java,swing,key-bindings,Java,Swing,Key Bindings,我有一个java程序,我对我的关键事件使用了KeyBinding。我也对我的JFrame使用了CardLayout 问题是,除非单击其他窗口并返回JFrame,否则KeyBindings不起作用。例如,我使用我的应用程序,使用Google Chrome,然后返回我的JFrame。然后键绑定工作 这是我的密码: package display.game; import java.awt.Color; import java.awt.event.ActionEvent; import java.a
package display.game;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Game extends JPanel {
private static final long serialVersionUID = 1L;
// ------VARIABLES-----//
@SuppressWarnings("unused")
private int _W = 1000;
private ImageIcon blue_paddle_img = new ImageIcon(getClass().getResource(
"res/PNG Files/paddle_blue.png"));
private Blue_Paddle blue_paddle = new Blue_Paddle(blue_paddle_img);
private ImageIcon red_paddle_img = new ImageIcon(getClass().getResource(
"res/PNG Files/paddle_red.png"));
private Red_Paddle red_paddle = new Red_Paddle(red_paddle_img);
public Game() {
setLayout(null);
addComponents();
setBackground(Color.BLACK);
setFocusable(true);
//KEYBINDING
setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, getInputMap());
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
getInputMap().put(key, "pressed");
getActionMap().put("pressed", new AbstractAction() {
public void actionPerformed(ActionEvent arg0) {
blue_paddle.move(0,5);
addComponents();
}
});
}
public void addComponents() {
blue_paddle.move(0, 0);
add(blue_paddle);
red_paddle.move(0, 0);
add(red_paddle);
}
}
当您的密钥绑定应该工作时,您期望什么?当您使用chrome时?问题是,小程序可能认为它没有焦点。切换时,您可以尝试使用
requestFocusInWindow
cards@htz不,我说我回到我的JFrame,然后按下键绑定中的按钮,啊,我的错。试试MadProgrammers suggestiongetInputMap(JComponent.WHEN_IN_FOCUSED_窗口).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN),“pressed”);