即使看起来失去焦点,JFrame 仍继续接收击键
我有一个 Java 应用程序,我将其称为“App”。应用程序偶尔会显示一个 JFrame,我们将其称为 myFrame。应用程序还将显示包含在 JDialog 或 JFrame 中的 JTextArea (我不确定是哪一个,但我可以找出回答这个问题是否有必要)。我们将此 JTextArea 称为“myTextArea”。
现在,发生以下事件序列:
- 我们显示 myFrame。它有焦点,你可以给它输入。
- 我们调用 myFrame.setVisible(false)
- 我们显示 myTextArea。
- 我们调用 myTextArea.requestFocus()。
- myTextArea 具有焦点(光标在其中闪烁),但输入的所有击键都会发送到 myFrame!
请注意,myTextArea 不包含在 myFrame 中。
这是怎么回事?有人听说过不可见的 JFrame 接收击键吗?不仅接收击键,还从其他具有焦点的组件中窃取它们?
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:
- We display myFrame. It has the focus and you can give it input.
- We call myFrame.setVisible(false)
- We display myTextArea.
- We call myTextArea.requestFocus().
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了导致问题的根本原因。
MyFrame
有一个实现KeyEventDispatcher
的类MyKeyEventHandler
。即使对于用于myTextArea
的击键,方法dispatchKeyEvent(KeyEvent e)
也始终返回 false。因此击键不会到达myTextArea
。I found what’s basically causing the problem.
MyFrame
has a classMyKeyEventHandler
that implementsKeyEventDispatcher
. The methoddispatchKeyEvent(KeyEvent e)
is always returning false even for key strokes that are intended formyTextArea
. Therefore the key strokes do not reachmyTextArea
.这与切换可见性无关。 JFrame 首先被初始化并且仍然具有焦点。你只是让它变得不可见,而不是夺走它的焦点。
此外,您的 JTextBox 需要有一个父容器。可能
应该有效。要将焦点转移到 JTextArea,请使用:
It is not about toggling the visibility. The JFrame is initialized first and still has focus. You are only making it invisible, not taking away the focus from it.
Moreover, your JTextBox needs to have a parent container. Possibly
should work. To shift the focus to the JTextArea, use :