DCS*_*oft 2 java swing awt keylistener
我的问题是,当我点击框架屏幕的空间时,它会停止键盘键被注册,所以我的播放器停止移动.
在此先感谢您的帮助.
代码:
private Component comp;
....
public InputManager(Component comp) {
this.comp = comp;
mouseLocation = new Point();
centerLocation = new Point();
// register key and mouse listeners
comp.addKeyListener(this);
comp.addMouseListener(this);
comp.addMouseMotionListener(this);
comp.addMouseWheelListener(this);
// allow input of the TAB key and other keys normally
// used for focus traversal
comp.setFocusTraversalKeysEnabled(false);
}
Run Code Online (Sandbox Code Playgroud)
GUI代码:
Game game = new Game();
game.setMinimumSize(new Dimension(WIDTH * 2, HEIGHT * 2));
game.setPreferredSize(new Dimension(WIDTH * 2, HEIGHT * 2));
game.setMaximumSize(new Dimension(WIDTH * 2, HEIGHT * 2));
frame = new JFrame(Game.NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(game);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
Run Code Online (Sandbox Code Playgroud)
我假设您正在使用KeyListener来侦听键输入.请注意,这仅在被收听的组件具有焦点时才有效,并且当您在JFrame上按下鼠标时,您收听的组件会失去焦点.
解决方案不是使用KeyListener,而是使用比KeyListener和更高级别概念更健壮的Key Bindings.
此外,您还想停止使用它作为您的监听器.如果你的程序不仅仅是一个玩具程序,那么维护一个将自己用作自己的监听器的GUI类变得非常困难.
此外,关于:"哦是的Game.java扩展Canvas":你不想不必要地混合AWT和Swing组件,因为这可能会导致副作用.相反,只需使用所有Swing组件,如JPanels而不是Canvases.