jmohrmann
jmohrmann

Reputation: 66

Is it possible to allow a JFrame to be focused without bringing it to the front every time?

I am trying to keep a certain JFrame on top of only one other JFrame, not all JFrames and JDialogs. Thus, I have jFrame1 and jFrame2. I want jFrame2 to always stay on top of jFrame1 even if I click buttons and do other things on jFrame1. However, if jFrame1 launches a dialog box, I do not want that dialog box to be hidden behind jFrame2. So, setting the "Always on Top" property for jFrame2 is not sufficient, since I want jFrame2 to only stay on top of jFrame1, not every frame and dialog.

So, that leads to my question: is it possible in Java to focus a JFrame (jFrame1) by clicking on it or however it happens, without simultaneously bringing it to the front (and thus covering jFrame2)? Essentially, I would like to do the opposite of this. I have tried a couple of solutions. One does not work and the other is nonideal.

My first attempt involved overriding the deprecated show() method in my jFrame1 so that it would not call the toFront() method. This did not work because, I presume, the show() method never gets called when a JFrame gains focus. My attempts to track down the location in the Java source code where any kind of toFront() or similar call is made when focus is gained did not yield any results. I am not sure where the "send to front" behavior is being called from when the focus is gained.

My second attempt works for what I want it to do, but has a nonideal side effect. This second solution involved implementing a WindowFocusListener on jFrame1 and then filling the windowGainedFocus(WindowEvent e) method with the following code, where shouldAlwaysBeOnTop() is simply the getter for a flag that indicates when I want this behavior to happen:

public void windowGainedFocus(WindowEvent e) {
    if (jFrame2.shouldAlwaysBeOnTop()) {
        jFrame2.toFront();
    }
}

This is basically this solution, and it does what I want it to do, but it involves first having the jFrame2 window be very briefly not shown (because it loses focus) and then very quickly shown again (because I call toFront() on it above)). This causes the jFrame2 window to "flash" or "blink" really fast every time jFrame1 is clicked on. Although otherwise this works how I want, the flashing behavior is not desirable. (When a dialog is displayed from jFrame1, then jFrame2 momentarily disappears until that dialog is dealt with and closed by the user. Then jFrame2 reappears. I am fine with this behavior but it is not necessary for jFrame2 to disappear in this instance - I am simply indifferent to it in this case).

So, is there a better way that I can have jFrame2 always be on top of jFrame1 while still being able to interact with jFrame1 and let it show dialog boxes that aren't covered by jFrame2 (whether or not the dialog box is on top of jFrame2 momentarily or jFrame2 momentarily disappears)?

Upvotes: 0

Views: 139

Answers (0)

Related Questions