Search code examples
javaswingjframejtextarea

JFrame continuing to receive key strokes even after seeming to lose focus


I have a Java app that I'll call App. App will occasionally display a JFrame that we'll call myFrame. App will also display a JTextArea that is contained in either a JDialog or a JFrame (I'm not sure which, but I can find out if that's necessary to answer this question). Let's call this JTextArea "myTextArea".

Now, the following sequence of events happens:

  1. We display myFrame. It has the focus and you can give it input.
  2. We call myFrame.setVisible(false)
  3. We display myTextArea.
  4. We call myTextArea.requestFocus().
  5. myTextArea has the focus (the cursor is blinking with in it), but all the keystrokes that are input are sent to myFrame!

Note that myTextArea is not contained in myFrame.

What is going on here? Has anyone heard of a non-visible JFrame receiving keystrokes? Not only receiving keystrokes but stealing them from some other component that has the focus?


Solution

  • I found what’s basically causing the problem. MyFrame has a class MyKeyEventHandler that implements KeyEventDispatcher. The method dispatchKeyEvent(KeyEvent e) is always returning false even for key strokes that are intended for myTextArea. Therefore the key strokes do not reach myTextArea.