0

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

1 回答 1

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方法。请参阅官方指南

于 2013-04-08T12:57:49.363 回答