Meaningless Drivel is fun!
The moose likes Applets and the fly likes Applet focus solution Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Applets
Bookmark "Applet focus solution" Watch "Applet focus solution" New topic

Applet focus solution

Darren Brooks
Ranch Hand

Joined: Dec 29, 2005
Posts: 32
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.

Daia Yum

Joined: Mar 23, 2009
Posts: 19

First, my class extends Applet and implements Runnable, so run() has the following statement inside the WHILE loop:

What is the while loop here.
I want to call a method when I press S key in the keyboard without using mouse.
But my applet is not getting the focus.
My Applet code is here.

Please help me out. Is anything wrong in my code???

I agree. Here's the link:
subject: Applet focus solution
It's not a secret anymore!