0

我的 Java 游戏有一个KeyBinding,我使用元键和 Z 键向左移动。

i.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 4), "Z");
m.put("Z", sprite_moveLeft);

我该如何写这个的发布形式?

i.put(KeyStroke.getKeyStroke(???????), "rZ");
m.put("rZ", sprite_rmoveLeft);

我已经试过了

i.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 4), "Z");
m.put("Z", sprite_moveLeft);
i.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 4, true), "rZ");
m.put("rZ", sprite_rmoveLeft);

但无济于事,并尝试将 KeyEvents 更改为键码(int)。

4

1 回答 1

3

尝试使用...

KeyStroke.getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease)

更新了工作示例

public class KeyBindingsTest {

    public static void main(String[] args) {
        new KeyBindingsTest();
    }

    public KeyBindingsTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new KeyBindingPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class KeyBindingPane extends JPanel {

        private JTextArea textArea;

        public KeyBindingPane() {
            setLayout(new BorderLayout());
            add(new JScrollPane((textArea = new JTextArea())));

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.ALT_DOWN_MASK, false), "Released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.ALT_DOWN_MASK, true), "Pressed");

            am.put("Released", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("released");
                    textArea.append("Released\n");
                }
            });
            am.put("Pressed", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("pressed");
                    textArea.append("Pressed\n");
                }
            });

            setFocusable(true);
            requestFocusInWindow();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 100);
        }
    }
}

请注意,我从未见过KeyEvent.META_DOWN_MASK在 Windows 上工作...

于 2013-01-10T19:14:32.650 回答