I conducted a fruitless search for solutions to getting my
applet to appear in a web page with focus (so the user doesn't first have to click on it to interact with it). Many others seem to have searched in vain, as well, so I thought I'd contribute my two bytes on this subject.
One post on JavaRanch suggested requestFocus(), yet this only works once the applet is active. Below is how I used this head start (if you will ;] ) to accomplish giving an applet focus.
Here is a solution that has worked for me (I would appreciate your thoughts):
First, my class extends Applet and implements Runnable, so run() has the following statement inside the WHILE loop:
As mentioned above, focusApplet() is called by a looping
thread instance in run() (e.g., a "timer"). This method is called repeatedly until hasFocus() == true. hasFocus() is an Applet method. One cannot set the focus on an Applet until is has become active (e.g., isActive() == true).
I have added some variables to check how long it takes for my Applet to become active; uncomment the System.out.println call and use a command line to open the applet to see the result (e.g., appletviewer applet.html).
By the way, Calling [if (!hasFocus()) focusApplet()] logic from inside run() is 8x faster than checking hasFocus() inside focusApplet() itself. The event seems to take literally nanoseconds to occur!
I made the method below synchronized - this seems to prevent an error when the applet shuts down (race condition? - I haven't really checked into it). It makes sense synchronizing the method. I hope some
java gurus will explain if this is not appropriate.