1 19 20 package org.netbeans.editor.ext; 21 22 import java.awt.Component ; 23 import java.awt.KeyboardFocusManager ; 24 import java.awt.event.KeyListener ; 25 import java.awt.event.KeyEvent ; 26 import java.util.LinkedList ; 27 import javax.swing.KeyStroke ; 28 import javax.swing.text.JTextComponent ; 29 30 34 public class KeyEventBlocker implements KeyListener { 35 36 private LinkedList blockedEvents = new LinkedList (); 37 private JTextComponent component; 38 private boolean discardKeyTyped = true; 39 private static final boolean debugBlockEvent 40 = Boolean.getBoolean("netbeans.debug.editor.blocker"); 42 43 public KeyEventBlocker(JTextComponent component, boolean discardFirstKeyTypedEvent) { 44 this.component = component; 45 this.discardKeyTyped = discardFirstKeyTypedEvent; 46 if (debugBlockEvent){ 47 System.out.println(""); System.out.println("attaching listener"+this.component.getClass()+" - "+this.component.hashCode()); } 50 this.component.addKeyListener(this); 51 } 52 53 54 public void stopBlocking(boolean dispatchBlockedEvents) { 55 if (debugBlockEvent){ 56 System.out.println("removing listener from "+this.component.getClass()+" - "+this.component.hashCode()); } 58 this.component.removeKeyListener(this); 59 if (dispatchBlockedEvents){ 60 KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); 61 while(!blockedEvents.isEmpty()) { 62 KeyEvent e = (KeyEvent )blockedEvents.removeFirst(); 63 e = new KeyEvent ((Component )e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation()); 64 kfm.dispatchEvent(e); 65 } 66 } 67 } 68 69 public void stopBlocking() { 70 stopBlocking(true); 71 } 72 73 public void keyPressed(KeyEvent e) { 74 if (debugBlockEvent){ 75 System.out.println("consuming keyPressed event:"+KeyEvent.getKeyModifiersText(e.getModifiers())+" + "+KeyEvent.getKeyText(e.getKeyCode())); } 77 e.consume(); 78 blockedEvents.add(e); 79 } 80 81 public void keyReleased(KeyEvent e) { 82 if (debugBlockEvent){ 83 System.out.println("consuming keyReleased event:"+KeyEvent.getKeyModifiersText(e.getModifiers())+" + "+KeyEvent.getKeyText(e.getKeyCode())); } 85 e.consume(); 86 blockedEvents.add(e); 87 } 88 89 public void keyTyped(KeyEvent e) { 90 if (debugBlockEvent){ 91 System.out.println("consuming keyTyped event:"+KeyEvent.getKeyModifiersText(e.getModifiers())+" + "+KeyEvent.getKeyText(e.getKeyCode())); } 93 e.consume(); 94 if (discardKeyTyped) { 95 discardKeyTyped = false; 96 } else { 97 blockedEvents.add(e); 98 } 99 } 100 } 101 | Popular Tags |