Java KeyEventDispatcher create

Description

Java KeyEventDispatcher create

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
   public static void main(String[] argv) throws Exception {
      JButton component = new JButton("a");

      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(component);/*w  ww. java 2  s. c  o  m*/
      f.pack();
      f.setVisible(true);

      KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
         public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_TYPED) {
               e.setKeyChar('a');
            }
            boolean discardEvent = false;
            return discardEvent;
         }
      });
   }
}



PreviousNext

Related