简体   繁体   中英

Java can't get KeyListener to work in my GUI

I am making a sort of remote control program for Lego EV3 robot. that part is irrelevant. So i made a GUI and i want to control the robot when i press keys. I understand that i have to use something called KeyListener and i even saw a tutorial which is supposed to work.

The GUI class code is right here. Kinda long but it has KeyPressed event at the end.

http://pastebin.com/QK639BDs

I am not sure what i am doing wrong but the program doesn't detect if any key is pressed at all. Any.

I would really appreciate any help on how to make that work.

EDIT:

keyManager=KeyboardFocusManager.getCurrentKeyboardFocusManager();
keyManager.addKeyEventDispatcher(new KeyEventDispatcher() {
        // UP:38  DOWN:40  LEFT:37  RIGHT:39
      public boolean dispatchKeyEvent(KeyEvent e) {
        if(e.getID()==KeyEvent.KEY_PRESSED && e.getKeyCode()==38){
          System.out.println("UP");
          return true;
        }
        if(e.getID()==KeyEvent.KEY_RELEASED&& e.getKeyCode()==38){
            System.out.println("RELEASED");
            return true;
        }

        return false;
      }

    });

So i browsed around and i found KeyboardFocusManger which is sort of working for me. I am testing it with a println. I am having only one problem. While i hold down the UP key i want it to only print UP once. Because the UP key will basically start the motor and it will keep moving until the key release will stop it.

Any ideas on how to do that?

KeyListener has issues, particularly with focus, so when any of your text fields are focused, your KeyListener won't respond, for example.

A better solution is to make use of the key bindings API, which allows you to control the level of focus required in order to trigger the key event. In combination with the Action API, you can define common actions for both your keys and buttons, for example.

Take a look at How to Use Key Bindings and How to Use Actions for more details.

Ps- I'm jealous and I wish you luck ;)

Do this:

frame.getContentPane().addKeyListener(this);

You may have to do it with different components depending on which one you want to have a key listener on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM