Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Applet focus solution

 
Darren Brooks
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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???
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic