Post keyevent to system event queue (AWT)

I recently came across an issue from a customer where an attempt to redirect a keyevent to another component (by posting it to the system event queue) resulted in an infinite recursion of the event getting posted.

 
Consider a simple scenario as below:

 
final EventQueue eventQ = Toolkit.getDefaultToolkit().getSystemEventQueue();

TextField tf = new TextField("This is a test"); tf.addKeyListener(new KeyAdapter() {
   public void keyPressed(KeyEvent ev) {
       KeyEvent keyevent = new KeyEvent (
          applet, ev.getID(), ev.getWhen(),
          ev.getModifiers(), ev.getKeyCode(), ev.getKeyChar()
       );
     System.out.println("keyPressed: " + ev.getClass());
     eventQ.postEvent(keyevent);
    }
});

Warning!  Running the above code may generate the keyPressed message on console infinite times.

Reason:

     Note that the keyevent on the textfield is being redirected to an applet. Users may normally expect the keyPressed event of the applet to get called as a result of this (assuming applet has implemented KeyListener) but that may not really happen in reality. In awt implementation, the keyevent is always sent to the focus owner. In this case obviously TextField is the focus owner at the point when keyPressed event is called. So even though an attempt is made to redirect the event to an applet, awt (internally) will post the event back to the focus owner (in this case TextField) and hence results in an infinite recursion.

Conclusion:

     Never post key event to a component until you are sure that the component is the focus owner

Solution:

     We strongly encourage developers to use KeyEventDispatcher (a keyevent preprocessor) or KeyEventPostProcessor (post processor) to handle such cases and redirect the event directly to the targetted component without posting it to the system event queue.
  

Thanks,
Kannan

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

kannan

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today