[英]Moving JFrame with arrow keys?
I want a normal JFrame that moves across the screen keys. 我想要一个在屏幕键上移动的普通JFrame。 It turns out not all that easy.
事实并非如此简单。
For some reason I get a rough code e.getKeyChar () 由于某种原因,我得到一个粗略的代码e.getKeyChar()
It is even possible? 甚至可能吗? I think that we have to somehow rewrite techniques, since I started, but there is something wrong.
我认为我们必须以某种方式重写技术,因为我开始,但有一些错误。
Prompt, adjust - 提示,调整 -
public class Main implements Runnable {
private int xLocation = 200;
private int yLocation = 200;
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Main());
}
@Override
public void run() {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new MyDispatcher());
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
JPanel panel = new JPanel();
panel.add(new JLabel("Label"));
panel.add(new JButton(new AbstractAction("Close") {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}));
frame.add(panel);
frame.pack();
frame.setLocation(xLocation, yLocation);
frame.setVisible(true);
}
private class MyDispatcher implements KeyEventDispatcher, KeyListener {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
char key = e.getKeyChar();
if(key==KeyEvent.VK_LEFT){
}
if (e.getID() == KeyEvent.KEY_PRESSED) {
//System.out.println("tester");
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
//System.out.println("2test2");
} else if (e.getID() == KeyEvent.KEY_TYPED) {
//System.out.println("3test3");
}
return false;
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("e.getKeyChar() " + e.getKeyChar());
char key = e.getKeyChar();
if (key == KeyEvent.VK_LEFT) {
xLocation += 5;
}
frame.setLocation(xLocation, yLocation);
frame.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
}
final JFrame jFrame = new JFrame();
jFrame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.VK_UNDEFINED), "moveRight");
jFrame.getRootPane().getActionMap().put("moveRight", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
jFrame.setLocation(jFrame.getX() + 5, jFrame.getY());
}
});
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
If you have ancestors inside your JFrame
than you should take the InputMap/ActionMap
approach. 如果你的
JFrame
有祖先,那么你应该使用InputMap/ActionMap
方法。 See the official guide . 请参阅官方指南 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.