1

I am trying to code a small module that allows user to enter a key by others keys (Key mapping) using NativeKeyListener. Mapping function is working fine but output always has 2 keys value (one is the key you press,one is mapped key). I only want mapped key value is entered.

This is my code:

public void nativeKeyPressed(NativeKeyEvent e) {

    String keyText = NativeKeyEvent.getKeyText(e.getKeyCode());

        if (keyText.equals("B")) {
            try {
                robot = new Robot();
                robot.setAutoDelay(0);
                robot.keyPress(103);

            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        } else if (keyText.equals("N")) {
            try {
                robot = new Robot();
                robot.setAutoDelay(0);
                robot.keyPress(104);
            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        }

Reality Output:

When I press "B": -> b7.

When I press "N". -> n8.

Expected Output:

When I press "B": -> 7.

When I press "N". -> 8.

An Nguyen
  • 288
  • 1
  • 15
  • 1
    Where does the output come from ? – Arnaud Dec 17 '18 at 07:18
  • focus on anywhere u want to enter a text :)). Its global key mapping – An Nguyen Dec 17 '18 at 07:19
  • It seems that you should consume the native event so that it doesn't get propagated and doesn't print the actual key value. Not sure if it is the solution, but still have a look at the piece of code here : https://github.com/kwhat/jnativehook/wiki/ConsumingEvents . Alternatively, you may try to issue a backspace key press : https://stackoverflow.com/questions/2596641/simulate-backspace-key-with-java-awt-robot – Arnaud Dec 17 '18 at 07:27
  • Sorry. it still produce the same result. – An Nguyen Dec 17 '18 at 07:44
  • I imagine that since `B` is still in the keyboard buffer, you'd get both values – MadProgrammer Dec 17 '18 at 07:51
  • then what should I do to stop window to execute the first event when I press B ? Thanks – An Nguyen Dec 17 '18 at 07:54
  • I think the problem is the window listener still listening the event whenever I press any keys – An Nguyen Dec 17 '18 at 08:03
  • @AnNguyen Sorry for late question. Did you solved your problem? – Neo Nov 25 '20 at 01:11

0 Answers0