• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 361
  • Last Modified:

Is there a KeyPreview equivalent in Java?

In other languages (.NET, Delphi, etc.) there's a KeyPreview option where you can flag it so that you can capture KeyPress events regardless of which component they take place in.  I can't seem to find an equivalent in Java.

I know that there's a swing KeyStroke object you can use to "bind" individual "actions" to a specific method, but this is definitely not what I'm looking for.  

So far, the only options I can see is either:
    1.) Overlaying an invisible object over the entire window, then manually handling all key events, focus, etc. in all objects (horrible).  
    2.) Add a static custom KeyInputListener to every single component in the application.  (Almost as horrible as 1, but not quite.)  
    3.) Create a KeyStroke "bind" for every conceivable keypress on every conceivable keyboard type.  Impossible.

Hoping for something much cleaner.
0
Javin007
Asked:
Javin007
  • 2
  • 2
1 Solution
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Put the following code somewhere in your Frame initialization (or somewhere else appropriate)...

        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatchKeyEvent(KeyEvent e) {
                System.out.println("ID: " + e.getID() + ", KeyCode: " + e.getKeyCode());
                return false;
            }
        });

Open in new window

0
 
Javin007Author Commented:
You are a God among men.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Thank you for that complement! ;) Glad to help
0
 
Javin007Author Commented:
No, seriously, every Java question I've had, you've got the right answer.  I just hope you're getting compensated appropriately in your god-ish java programming job.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now