用箭头键移动JFrame?

时间:2013-04-08 06:54:07

标签: java swing jframe keylistener

我想要一个在屏幕键上移动的普通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) {
        }        
    }
}

1 个答案:

答案 0 :(得分:2)

    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);

如果您的JFrame内有祖先,则应采用InputMap/ActionMap方法。见官方guide