0
我想要一個正常的JFrame在屏幕上移動。事實證明,並不是那麼容易。用箭頭鍵移動JFrame?
出於某種原因,我得到一個粗略的代碼e.getKeyChar()
甚至有可能?我認爲自從我開始以來,我們不得不重寫技術,但是有一些錯誤。
提示,調整 -
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) {
}
}
}