Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bring JFrame to front but NOT focus?

Tags:

java

swing

jframe

I'm writing a Java app (Swing GUI) that periodically pops up a JFrame.

Is it possible somehow to bring the window to front (foo.setAlwaysOnTop(true) would be even better) but without having it focus?

Some people move their eyes away from the screen from time to time to look at their keyboard while typing, and I'm sure that if this window would always capture the keyboard focus people would get really annoyed as it's causing them to lose quite a few keystrokes every time it pops up unnoticed.

In other cases, even when the user is actually capable of typing without looking at the keyboard all the time, having a window pop up and get focus could cause unwanted actions from the pop-up window itself (some Tab+Enter combination for example, where the user accidentally selects an option she really wouldn't had selected otherwise).

Thanks in advance!

Update

As Jonas suggests, foo.setFocusableWindowState(false); seems to work if called after the window has been rendered (tested on Gnome only).

This does not work:

foo.setFocusableWindowState(false);
foo.setVisible(true);
foo.setFocusableWindowState(true);

However, this does:

foo.setFocusableWindowState(false);
foo.setVisible(true);
Thread.sleep(1000);
foo.setFocusableWindowState(true);

I'll have to see if there's an event I can catch/listen to that allows me to do foo.setFocusableWindowStatue(true); when appropriate.

I consider my problem solved.

like image 417
Johann Fridriksson Avatar asked Jan 25 '11 00:01

Johann Fridriksson


People also ask

How do you make a JFrame appear in the middle of the screen?

Just click on form and go to JFrame properties, then Code tab and check Generate Center .

What is difference between JFrame and Swing?

A JFrame is a Swing component which is the newer one, well today's java GUI development uses mostly Swing as an advantage you can have a lot of community support on it. as far as I know Swing has LookAndFeel Feature that you can configure to change the look of your GUI with just few line of codes.

Does JFrame contain Swing?

The JFrame class is slightly incompatible with Frame . Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame . This is different from the AWT Frame case.


2 Answers

This may work:

foo.setFocusableWindowState(false);
like image 175
Jonas Avatar answered Oct 12 '22 12:10

Jonas


As of Java 1.7 you can call

frame.setAutoRequestFocus(false);
like image 44
Daniel Avatar answered Oct 12 '22 12:10

Daniel