简体   繁体   中英

How do I lose the focus on a JFrame?

I'm making some kind of on-screen keyboard in java. So I need the JFrame to lose focus (and thus, transfer focus to the next window) to send the key strokes. Is there a way to make the JFrame window lose focus?

For example, on Windows, if you open the native on-screen keyboard, you can press the buttons on there while the on-screen window itself is not in focus but instead, a different window gets the input. 在此输入图像描述

For clarity, I'm trying to replicate what the native on-screen keyboard does. So the one I'm making will be used on any and all windows that I have open, not just Java. I'm using the Robot class to simulate the keystrokes.

To sum it off, I need my JFrame to:

  • Stay on top of other windows (Done. By using setAlwaysOnTop(true); )
  • Not have focus (So the key strokes can be send to whatever the top-level window is at the moment instead)

I can't believe how stupid I am, the answer was right there. I don't know how I missed it but setFocusableWindowState(false); is what I was looking for. Using that flag on the JFrame, it doesn't get focused.

I'm guessing that your second window is another JFrame, perhaps? If so, put your secondary window in a JDialog that is linked to the primary main JFrame (that is, you pass the JFrame into the JDialog's constructor). This will give you exactly what you want.

For more specific help, consider creating a very simple and small example program that demonstrates your problem. It could have just one JButton on the dialog window for instance, an sscce .


Edit
After reading your updated question, I fear that your problem can not be solved with core Java and will require some native coding, perhaps through JNI or JNA. Please understand that in order for Java to be usable on multiple platforms, it was built to be as OS agnostic as possible and thus is required to be isolated from low-level OS calls, calls that would be required for your desired program to work.

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