java.awt.event.KeyEvent不能完全映射AZERTY键盘?

时间:2013-09-03 19:25:02

标签: java swing awt keyevent

你好我做了一个java程序,每次按一个键都会显示keyEvent.getKeyCode()。

目的是能够使用java机器人类和一些keyEvent使某种机器人能够驱动git / skyrim / fraps。

然而它似乎无法映射AZERTY键盘,因为你可以看到一些keyEvent代码是相同的。

azerty mapped

有没有其他方法可以驱动键盘?

如果你想知道这是程序:

主要课程:

package keykeykey;
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);

    JTextField codeTextField = new JTextField();
    frame.add(codeTextField, BorderLayout.SOUTH);

    MyKeyListener myKeyListener = new MyKeyListener(codeTextField, nameTextField);
    nameTextField.addKeyListener(myKeyListener);

    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}

keyListener重新定义

package keykeykey;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

public class MyKeyListener extends KeyAdapter implements KeyListener {

    public JTextField codeTextField;
    public JTextField writeTextField;

    public MyKeyListener(JTextField codeTextField, JTextField writeTextField) {
        this.codeTextField = codeTextField;
        this.writeTextField = writeTextField;
    }

    @Override
    public void keyPressed(KeyEvent keyEvent) {
    printIt("Pressed", keyEvent);
    codeTextField.setText("code = " + keyEvent.getKeyCode());
  }

  @Override
    public void keyReleased(KeyEvent keyEvent) {
    codeTextField.setText("");
    writeTextField.setText("");
  }

  @Override
    public void keyTyped(KeyEvent keyEvent) {
    //do nothing
  }

  private void printIt(String title, KeyEvent keyEvent) {
    int keyCode = keyEvent.getKeyCode();
    String keyText = KeyEvent.getKeyText(keyCode);
    System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar() + " code = " + keyEvent.getKeyCode());
  }

}

感谢。

Ps:是的我知道autoHotKey,但我需要一种强类型的语言,我喜欢java。

修改

我一定没有正确表达自己,我知道shift + VK1为“1”,其他键也是如此。

我的问题在于,正如您在第一张图片中看到的,某些键会生成无法识别的键事件(带有红条的键)。

例如那两个键:

unknown key code

1 个答案:

答案 0 :(得分:1)

可以根据应用的修改器更改虚拟键。实际结果取决于键盘驱动程序本身,但例如......

Shift + 1 会生成KeyEvent keyCodeKeyEvent.VK_1,但其keyChar! {1}}

你基本上忽略了这些修饰符......

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestKeyStrokes {

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

    public TestKeyStrokes() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

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

    public class TestPane extends JPanel {

        private JList keyList;
        private DefaultListModel<String> model;

        public TestPane() {
            setLayout(new BorderLayout());
            model = new DefaultListModel<>();
            keyList = new JList(model);
            add(new JScrollPane(keyList));
            keyList.addKeyListener(new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {
                }

                @Override
                public void keyPressed(KeyEvent e) {
                }

                @Override
                public void keyReleased(KeyEvent e) {
                    StringBuilder sb = new StringBuilder(64);
                    if (e.isShiftDown()) {
                        sb.append("[SHIFT]");
                    } else if (e.isAltDown()) {
                        sb.append("[ALT]");
                    } else if (e.isControlDown()) {
                        sb.append("[CTRL]");
                    } else if (e.isAltGraphDown()) {
                        sb.append("[ALT-GRPH]");
                    } else if (e.isMetaDown()) {
                        sb.append("[META]");
                    }
                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_SHIFT:
                        case KeyEvent.VK_ALT:
                        case KeyEvent.VK_CONTROL:
                        case KeyEvent.VK_ALT_GRAPH:
                        case KeyEvent.VK_META:
                            break;
                        default:
                            sb.append("[").append(getVKText(e.getKeyCode())).append("/").append(e.getKeyChar()).append("]");
                            break;
                    }

                    model.addElement(sb.toString());
                }
            });
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.dispose();
        }
    }

    private static VKCollection vKCollection;

    static VKCollection getVKCollection() {
        if (vKCollection == null) {
            vKCollection = new VKCollection();
        }
        return vKCollection;
    }

    static String getVKText(int keyCode) {
        VKCollection vkCollect = getVKCollection();
        Integer key = Integer.valueOf(keyCode);
        String name = vkCollect.findName(key);
        if (name != null) {
            return name.substring(3);
        }
        int expected_modifiers
                = (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL);

        Field[] fields = KeyEvent.class.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                if (fields[i].getModifiers() == expected_modifiers
                        && fields[i].getType() == Integer.TYPE
                        && fields[i].getName().startsWith("VK_")
                        && fields[i].getInt(KeyEvent.class) == keyCode) {
                    name = fields[i].getName();
                    vkCollect.put(name, key);
                    return name.substring(3);
                }
            } catch (IllegalAccessException e) {
                assert (false);
            }
        }
        return "UNKNOWN";
    }

    static class VKCollection {

        Map code2name;
        Map name2code;

        public VKCollection() {
            code2name = new HashMap();
            name2code = new HashMap();
        }

        public synchronized void put(String name, Integer code) {
            assert ((name != null) && (code != null));
            assert (findName(code) == null);
            assert (findCode(name) == null);
            code2name.put(code, name);
            name2code.put(name, code);
        }

        public synchronized Integer findCode(String name) {
            assert (name != null);
            return (Integer) name2code.get(name);
        }

        public synchronized String findName(Integer code) {
            assert (code != null);
            return (String) code2name.get(code);
        }
    }
}