views:

349

answers:

2

My app is a JApplet which opens a JFrame. the applet has a listener and a button, so that if the frame goes behind another window (looses focus), the user can simply click the button to get it to come to the front. frame.toFront(); This works fine.

But initially (in the applet's public void init() {}), after calling frame.setVisible(true); I call frame.toFront(); to to make sure it starts in front. However, the frame then immediately goes behind the browser. Pressing the button calls it back, though. I have tried a running a separate thread which repeatedly calls frame.toFront(); But as soon as this stops, the frame goes behind the browser anyways. Only when the button is pressed does it come to the front, and stay in front. Also, having a loop or time continually holding it in front is not a good option, because the user may need or want to have it go behind on purpose. This "bug" is not present on the Mac (which runs Java 1.5), but on Windows (running 1.6) - including IE, FF, Chrome, Safari, but not Opera (strangely).

Possible cause and fix?

A: 

Have you tried setAlwaysOnTop(true) on the frame? I'm not sure however, if this is allowed on frames or windows created from an applet.

jarnbjo
No, it's not allowed.
Tom Hawtin - tackline
A: 

The setAlwaysOnTop(true) solves one problem, but create another, namely that now there is no way for the user to actually send the window to the back.

My sollution is a hack: In the WindowListener attached to the JFrame, place this code:

@Override
public void windowDeactivated(WindowEvent e)
{
  if(firstToBack)  //firstToBack is an bloolean instance variable initialized to true
  {
    final JFrame f = frame;
    new Thread() { public void run() {
      try { Thread.sleep(300); } catch(InterruptedException ie) {}  
      f.toFront();
    }}.start();
    firstToBack = false;
  } 
}

This basically starts a new Thread first time, which waits a little and then calls the JFrame to the front. It only executes once, so the frame doesn't keep coming to the front every time the user sends it to the back. The 300 milliseconds is an arbitrary amount of time and perhaps not even necessary.

Perhaps someone can tell me why this works, but when the same kind of thread was started fron the applet's init() method, the window went to the back anyways, after the thread ended?

Terje Dahl