0

I have a JFrame with multiple components on it, and I am not able to have the keyPressed event from the JFrame called because the frame is never focused, and the event only works when it is focused. How should I make a similar event but only have it work when the window is focused, not just the individual component?

foo bar
  • 75
  • 6
  • 2
    Have a look at [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Aug 20 '15 at 03:46
  • @AndrewThompson It is the answer, but it'd be a link only answer, so :( - but yes, it might be a good close reason as nothing else is going to answer the question – MadProgrammer Aug 20 '15 at 03:50
  • 2
    I'm voting to close this question as off-topic because the question can best be answered by reading the [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) tutorial – MadProgrammer Aug 20 '15 at 03:50

2 Answers2

0

I found a thread on this site that does it extremely easily, no need for key bindings or anything. All this thing is, is an overrided method of dispatchKeyEvent; I don't know if this is the best way of doing it, but it works for me

Here's a link to the thread How can I listen for key presses (within Java Swing) across all components?

KeyboardFocusManager.getCurrentKeyboardFocusManager()
    .addKeyEventDispatcher(new KeyEventDispatcher() {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            System.out.println("Got key event!");
            return false;
        }
    });
Community
  • 1
  • 1
foo bar
  • 75
  • 6
0

The easiest way would be to place a JPanel in the JFrame, then do everything using that JPanel instead of the JFrame.

FredK
  • 4,094
  • 1
  • 9
  • 11