Catching key events in application

I have a JFrame with a JDesktop containing lots of JInternalFrame with various of components such as JTextFields etc.
Now, i want to have a "main" listener that will catch key events no matter which component that has focus. For example pressing CTRL+A should produce something in the application no matter which component that has focus.
How do I implement this in an easy way?

It doesnt seem to work to add a KeyListener to the JFrame...
this.addKeyListener(new KeyAdapter(){
               public void keyTyped(KeyEvent e){
                    System.out.println("KeyTyped()");
               public void keyPressed(KeyEvent e){
                    System.out.println("KeyTyped()");
          });Adding that to the JFrame gives nothing to System.out when a JTextArea inside an JInternalFrame has focus.

Similar Messages

  • How to catch key events in JWindow???

    Can somebody please suggest me how do I catch key events in a JWindow. I tried without success with addKeyListener( ) method. My sample code is attached below. I've j2sdk1.4.2_03 in my PC.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class EventCatcher extends JWindow implements KeyListener {
         public EventCatcher() {
              super();
              Container c = getContentPane();
              setBounds(100,100,400,400);
              c.setLayout(new FlowLayout());
              JButton button = new JButton("Hello");
              c.add(button);
    addKeyListener(this);
    requestFocus();
    setVisible(true);
         public void keyReleased(KeyEvent ke) {
    System.out.println("**************");
         public void keyPressed(KeyEvent ke) {}
         public void keyTyped(KeyEvent ke) {}
         public static void main(String str[]) {
              new EventCatcher();
    Regards,
    Koushik

    Hi GraemeHook!
    This is Khurram. I tried your code on my problem that is 95% like this problem but it could not be solved.
    can u please take view on my code.
    I m trying to move a frame that extends from JWindow on runtime with Key Board Arrow keys. but this only works when I extend this MainApp class from JFrame, but not when from JWindow.
    can u please help me. I also posted my own topic but no one response so found it resambling to my problem.
    hoping to hear from u soon
    you can also tell me at my email address
    [email protected]
    thanks
    ===========================================================
    MainApp.java
    *MainApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class MainApp extends JWindow {
      static LocationManager appLoc = new LocationManager();
      public MainApp() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String[] args) {
       MainApp frm = new MainApp();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int width = screenSize.width;
            int height = 45;
              frm.setFocusableWindowState(true);
            frm.setFocusable(true);
            frm.setSize(width, height);
            frm.setLocation(appLoc.setAppAtBottomCentered(width, height));
            frm.setLocation(appLoc.moveAppUpward(100));
            frm.setVisible(true);
      private void jbInit() throws Exception {
        this.getContentPane().setBackground(Color.white);
         addKeyListener(new java.awt.event.KeyAdapter(){
          int moveSpeed = 4;//must be even
          public void keyPressed(KeyEvent e){
            //JOptionPane.showMessageDialog(null,""+e.getKeyCode());
             if(e.getKeyCode() == KeyEvent.VK_SHIFT)
              if(moveSpeed==4)
                moveSpeed = 12;
              else
                moveSpeed = 4;
            if(e.getKeyCode() == KeyEvent.VK_UP)
              setLocation(appLoc.moveAppUpward(moveSpeed));
            else if(e.getKeyCode() == KeyEvent.VK_DOWN)
              setLocation(appLoc.moveAppDownward(moveSpeed));
            else if(e.getKeyCode() == KeyEvent.VK_LEFT)
              setLocation(appLoc.moveAppToLeft(moveSpeed));
            else if(e.getKeyCode() == KeyEvent.VK_RIGHT)
              setLocation(appLoc.moveAppToRight(moveSpeed));
            else if(e.getKeyCode() == 107) {//NUMPAD '+' Key For Vertically Increasing
              setSize(appLoc.increaseSize(0,moveSpeed));
              setLocation(appLoc.updateLocation());
            else if(e.getKeyCode() == 109) {//NUMPAD '-' Key For Vertically Decreasing
              setSize(appLoc.decreaseSize(0,moveSpeed));
              setLocation(appLoc.updateLocation());
            else if(e.getKeyCode() == 61) {// '+' Key For Horizontal Increasing
              setSize(appLoc.increaseSize(moveSpeed,0));
              setLocation(appLoc.updateLocation());
            else if(e.getKeyCode() == 45) {// '-' Key For Horizontal Decreasing
              setSize(appLoc.decreaseSize(moveSpeed,0));
              setLocation(appLoc.updateLocation());
    }====================================================================
    LocationManager.java
    * LocationManager.java
        import java.awt.*;
        import java.awt.event.*;
        import javax.swing.*;
        import java.util.*;
        import java.sql.*;
    public class LocationManager {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        static Point newPoint = new Point();
        static Dimension newDim = new Dimension();
        static Dimension minDim = new Dimension();
        /** Creates a new instance of LocationManager */
        public LocationManager() {
        public LocationManager(int width, int height){
            this.setAppCenteredWithDim(width, height);
        public Point setAppCenteredWithDim(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width)/2;
            newPoint.y = (sHeight-height)/2;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtTopCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width)/2;
            newPoint.y = 0;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtBottomCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width)/2;
            newPoint.y = (sHeight-height);
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtRightCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = 0;
            newPoint.y = (sHeight-height)/2;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtLeftCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width);
            newPoint.y = (sHeight-height)/2;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppUpward(int step){
            newPoint.y -= step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppDownward(int step){
            newPoint.y += step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppToLeft(int step){
            newPoint.x -= step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppToRight(int step){
            newPoint.x += step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Dimension increaseSize(int w, int h){
          minDim.width = 116;
          minDim.height = 56;
          newDim.width += w;
          newDim.height +=h;
          if(w==0 && newDim.height > minDim.height)
            newPoint.y -= h/2;
          else if(newDim.width > minDim.width )
            newPoint.x -= w/2;
          return newDim;
        public Dimension decreaseSize(int w, int h){
          minDim.width = 116;
          minDim.height = 56;
          if(newDim.width > minDim.width )
            newDim.width -= w;
          if(newDim.height > minDim.height)
            newDim.height -= h;
          if(w==0 && newDim.height > minDim.height)
            newPoint.y += h/2;
          else if(newDim.width > minDim.width)
            newPoint.x += w/2;
          return newDim;
        public Point updateLocation(){
          return newPoint;
            //return new Point(this.x, this.y);
    }===================================================================

  • How to catch key events

    Hello!
    I have a component which extends JPanel. Now I dynamically add a JTextField as a child to this component. The problem is: when the textfield has focus, how can I get key events in my panel before the textfield gets them (and maybe intercept them so that the textfield doesn't get them at all)?
    Background: the component is a self written table and the textfield is an editor. Now I have to make sure that when I am editing and press e.g. "cursor up", that not the textfield will get this key event but the table (which should traverse the current cell then ...)
    The problem is: I cannot change the textfield (extend it or something) because a possible solution has to work with any java awt "Component" (or at least with JComponent).
    Any help very appreciated.
    Michael

    Hello,
    implement the keyListener interface for the Extended component...
    and in Keypressed method
    keyPressed(keyEvent){
    // do all ur reuirements here
    //and comsume the keyEvent...
    hope this helps

  • Catch key events

    Hi there, is there a way to catch all the keys typed on the keyboard, and not only the events on a focused component? I would like to implement some kind of shortcut key wich works everywhere. I dont know a great deal about C, but I think I would have to implement that mechanism in c and wrap it with JNI. can anyone tell me how to start off?

    Hi there, is there a way to catch all the keys typed on the keyboard, and not only the events on a focused component? I would like to implement some kind of shortcut key wich works everywhere. I dont know a great deal about C, but I think I would have to implement that mechanism in c and wrap it with JNI. can anyone tell me how to start off?

  • How to implement "ALT + some key" event ?

    Hello,
    I'd like JDialog to catch key events only when user holds ALT button and presses some regular key (e.g. A,B,C, etc...).
    How this can be done ?
    Thanks for any advice !

    maybe you should use mnemonics?
    i don't know what is it you want to do.
    buti if you want for example to have JDialog, where are some buttons (OK & CANCEL) and want user to be able to click them by pressing ALT+O or ALT+C, then you might need to use mnemonics...
    if you want to enable some new kind of copy/paste/whatever combinations, then you might want to use keybindings
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    or see tutorial about using menus, and the part there which tells about enabling key operations
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#mnemonic
    or be more specific about your problem... what and Why are you trying to do.

  • Key events in a form

    Hello!
    Maybe I'm missing it, but how can one catch key events on a form?

    One way is to create a CustomItem and add this method:
    protected void keyPressed(int key) {
        System.out.println("Key pressed: "+key);
    }This will print the value of the key pressed when the CustomItem is focused.

  • Catch KeyDown events for modifier keys

    I need to be able to tell when a user presses or releases the CTRL key for my application, but I can't get KeyListeners to work and the key bindings only appear to work with releasing the key. I also have key bindings for CTRL key combinations (like CTRL-N, CTRL-S, etc.), but I need an event which is fired when the user first presses the CTRL key. The goal is to have a tooltip on my custom JPanel which pops up when I press CTRL and goes away when I release it.
    My (broken) key binding code:
    JPanel main=new JPanel();
    InputMap im=main.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(KeyStroke.getKeyStroke("pressed CONTROL"), "cDown");
    im.put(KeyStroke.getKeyStroke("released CONTROL"), "cUp");
    main.getActionMap().put("cDown",new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            isCtrlDown=true;
            updateTooltip();
            System.out.println("down");
    main.getActionMap().put("cUp",new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            isCtrlDown=false;
            updateTooltip();
            System.out.println("up");
    });If you press the control key a few times over this component, you only get "up" printed.

    Hi BaconOppenheim,
    Could you let me know which locale/input source you're using? I've run through some tests with the configuration you mentioned and I'm not seeing a problem. There is an issue with Ctrl+Click as that triggers a right click on Mac but the Alt key is certainly working on mouse events.
    Could you send a screen shot of the test extension output after running:
    1. Click + Shift key down
    2. Click + Alt key down
    3. Click + Cmd key down
    4. Click + Shift key + Alt key + Cmd key down
    That should cover the cases and show me the exact results.
    Thanks,
    Greg

  • Catch several key events

    hi...how do i catch several keys events?
    Example:
    i have a menubar with a menuitem Pan and need to catch the keys UP,DOWN,RIGHT,LEFT.
    I know how to catch one key using a menushortcut.
    Thanks.

    Like this :
    menubaritem.addKeyListener(new KeyListener(){
       public void keyPressed(KeyEvent evt){
          int keyCode = evt.getKeyCode();
          switch(keyCode){
             case KeyEvent.VK_UP:
                //your code here...
                break;
             case KeyEvent.VK_DOWN:
                //your code here...
                break;
             case KeyEvent.VK_LEFT:
                //your code here
                break;
             case KeyEvent.VK_RIGHT:
                //your code here
                break;
       public void keyTyped(KeyEvent evt){}
       public void keyReleased(KeyEvent evt){}

  • Catch a key event in JFrame

    hi,
    i am coding a GUI application for some FSM(Finite State Machine) simulation purpose. the app can load the FSM and display it. i can selecte some part of FSM and using "delete" key to delete the selected states. i did register the KeyEventListener to the the JFrame. but when i try to press the "del" key the app doesn't do anything. after few tests, i think JFrame never listene to my key event. how can i make it possible to let the JFrame to listene to my "key event"?
    Thanks~~~

    Read this, it is very useful for things like this:
    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings
    In your case you can add a key binding to the frame's root pane, and bind the delete key to the action you want to perform.

  • Catch event when Application Server is shutdown

    Hi All,
    Actually I want to catch an event do something when weblogic server is shutdown.
    How can I catch the event.
    Any help would be highly appreciated.
    I tried by implementing ServletContextListener interface, but in that I can only catch the event when weblogic is started, but not when it is shutdown.

    Create a class that implements the ServletContextListener interface:
         public class myServletContextListener implements ServletContextListener
    The ServletContextListener interface has two methods that must be implemented:
         public void contextInitialized(ServletContextEvent sce)
         public void contextDestoyed(ServletContextEvent sce)
    Register the listener in the web.xml:
         <web-app>
              <context-param>
                   <param-name>param1</param-name>
                   <param-value>paramValue1<param-value>
              </context-param>
              <listener>
                                                     <listener-class>
                                                                com.listeners.MyServletContextAttributeListener
                     </listener-class>
              </listener>
              <servlet>
                   <servlet-name>test</servlet-name>
                   <servlet-class>com.test</servlet-class>
                   <init-param>
                        <param-name>param1</param-name>
                        <param-value>paramValue1</param-value>
                   </init-param>
                   <load-on-startup>1</load-on-startup>
              </servlet>
              <servlet-mapping>
                   <servlet-name>test</servlet-name>
                   <url-pattern>/test</url-pattern>
              </servlet-mapping>
         </web-app>When the server starts up the servlet context (usually on server start up) it will call the contextInitialized method of your myServletContextListener class. When the server shuts down the servlet context (usually on server shutdown) it will call the contextDestroyed method of your myServletContextListener class.
    With in these methods you can usually assume that the server is starting/stopping and do what it is you wish to do.
    However there are two things to bear in mind:
    1- Most servers offer a manager app that allows individual servlet contexts to be stopped/started without shutting down the server o you may get false results depending on you is managing the server.
    2- I am not sure if the methods will be called if the server suffers a catastrophic error and crashes. For example a out of memory error. So you may miss a server shut down but the error should be logged in the tomcat log files.

  • Which components catch a key-event?

    Hello,
    I've a question. I've a panel with severall sub-panels with textfield-editors. These have listeners to respond on a enter-key pressed event.
    When I input an illegal value somewhere, I invoke a messagedialog with a warning message. The problem is that when I press enter , the oke-button of the messagepane has the focus, the enter-key pressed event is also caught by my first panel with all the editors and shows the same message dialog again. Kinda like a loop.
    I thought that key-pressed event only where caught by the component/frame which has the focus, or am I wrong.
    Can anyone help me out here?
    Much Thanks
    Hugo Hendriks

    Normally an ActionListener is installed to an OK button, not a KeyListener. Check if you have implemented the same error handling in two places!
    Generally you can "eat" key events by e.consume(), maybe this helps:
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    // ... do some error handling on ENTER
    e.consume();
    I think then the Frame GUI will no get the key event anymore. A modal JDialog has a local event queue (to be modal), but maybe it forwards events to the main queue ...

  • Adobe Air for Android - caching key event that have "unusual" keycode

    I am developing an application for a platform. The OS of this platform is Android Gingerbread (2.3.4) The platform has some buttons with "unusual" key code: 141, 131 etc.
    Native application that created in ADT can catch and respond to these keyboard events While my Adobe AIR application (created in Flash professional) are Indifferent to them.
    I try both: stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyHandler,false,0,true); NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN,KeyHandler,fa lse,0,true);
    How can I "catch" this event? Maybe a way to add constant to the keyboard class?
    Thanks

    If you are deploying for iPhone it is on the 'general' settings(First setting page opened).
    Just noticed you are making android app but i still added iphone deployment settings for further future
    But if you are using it for flash/android you have to add code into your fla descriptor with XML language(dont worry it is 1 line of code)
    Watch the video on this page about GPU rendering:
    http://blogs.adobe.com/cantrell/archives/2010/10/gpu-rendering-in-adobe-air-for-android.ht ml
    Your app shouldn't lag after these steps but if you have a project that gets bigger and has lots of code it MIGHT lag so that is when external files should help.

  • How to listen a key event without having any window component

    Hi all,
    I would like to know how can I listen key events from an application that doesn't use windows
    Thanks

    yoiu can make a Thread run inside your application. This will listen for inputs in the command line. For examplethis is part of a chat server (on the console) with let the server manager to enter messages or commands.
    The message or command entered on the console by the user is catched and processed as a String. The string is passed to the processConsole() method, you must define yourself.
    Th Thread is never stopped, so the user may enter any message at any time
    The core of you application should also be a Thread for better performance, but maybe it will also work without. Jst try and provide needed importstatements.
    Runnable runInput = new Runnable() {
            public void run() {
              while(true) {
                try {
                  byte buffer[] = new byte[255];
                  System.out.print(prompt);
                  System.in.read(buffer);//, 0, 255);
                  String inputString = new String(buffer, "Default");
                  processConsole(inputString);
                catch(NullPointerException npe) {
                  System.out.println("Syntax error");
                catch(Exception e) {e.printStackTrace(); }
          Thread inputThread = new Thread(runInput);
          inputThread.start();

  • Associating key events to a TextBox

    Hello All!
    Can anybody tell me how to associate key events with a TextBox? Something like when a certain key is pressed and released, a certain combinations of characters is inserted e.g. =-)
    I am trying to develop a simple application that allows users to type text with non-English characters, e.g. Russian and for that I have created a canvas and I am using key events i.e. KeyPressed and KeyReleased methods. Using a canvas is a bit insufficient because users cannot move the cursor freely through the text.
    I have read on te web that I can create a CustomeItem and override the KeyPressed methods but I could not do it; I could not find any simlar code example.
    Can anybody help me by providing me with a simple example or suggesting me an alternative way?
    Many thanks in advance

    {color:#008080}*Hello again!*
    I managed to create a CustomItem that overrides KeyPressed method, but now I am having difficulties making my textBox reacts to my keyPressed method.
    The early version of this CustomeItem overrides the KeyPressed method by assigning each key to a certain collection of chars. When a key is pressed, a string of these chars is drawn on the Canvas, which works fine. Now because I want to be able to edit the text, e.g. delete a certain char in the middle of the string, I want to use a TextBox or a TextField. The current problem is that my TextBox does not react to my key presses the way I want (I used setString() method); it reacts to the original key presses which print the original chars (from A through to Z and 1 through to 9).
    Is it possible to set the contents of a TextBox or TextField depending on my key presses? Could you suggest me an alternative way?
    Many thanks in advance!!{color}

  • No key event when compose keys are pressed

    I am supporting a legacy application for Sabre which maps some of the keys differently. For example, on a French keyboard the Compose key which is used to put a ^ on top of the vowel characters is to be remapped to produce a special character called a "Change Character" that has a special use for reservation agents that use Sabre
    The problem is, the first time you press the ^ compose key there is no key event apparently because the VM figures it doesn't yet know what key to report, it is expecting you to press a character such as 'o' and then you get an 'o' with a '^' on top of it.
    If you press the ^ compose key a second time, you get the following key events:
    keyPressed
    keyTyped
    keyTyped
    keyReleased
    On the screen you will see two ^ characters appear. Currently I remap the ^ character to the "Change Character", and I suppress the second keyTyped event so that I only get one character. The problem is that the user ends up having to press the key twice to get one "Change Character."
    I have no fix for this problem because there is no key event produced when they press the ^ compose key the first time.
    By the way, this behavior appears to have been introduced with jdk 1.3. The older jdk did produce a key event the first time you pressed the compose key. I would expect that this behavior was considered to be a bug and was fixed in jdk 1.3.
    Is there some other way to detect when the user presses a compose key? If not, is it possible for future jdk releases to report a keyPressed event when a compose key is pressed? This event would not cause a character to appear on the screen, but would allow programs to detect when the compose key is pressed.
    There is already a key on the French keyboard that behaves this way. It is the key to the left of the '1' key and it has the pipe symbol on it. If you press Shift plus this pipe key, no character is produces but a keyPressed event with a keycode of 222 is produced. I merely point this out to show that there is a way to report key events whithout producing output on the screen.
    Thanks, Brian Bruderer

    I don't know if this actually helps, but it seems that you can bind an Action to a dead key like the circumflex of the French keyboard
    Keymap keymap = textPane.addKeymap("MyEmacsBindings", textPane.getKeymap());
    Action action = getActionByName(DefaultEditorKit.beginAction );
    KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_DEAD_CIRCUMFLEX);
    keymap.addActionForKeyStroke(key, action);I saw this on a Swing tutorial and modified it slightly. Have a look at it :
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html
    Chris

Maybe you are looking for

  • How do I back up my iPhoto library to disc?

    I looked this up, and it said to select the pics I wanted to back up, then click on Share, Burn. Problem is, all the options, including Burn, are grayed out. Does anybody know the "trick" to get this to work?

  • Acrobat Pro 9 & XI both installed on Mac. How can I uninstall Acrobat Pro 9 & not affect Acrobat XI?

    Adobe Acrobat Pro 9 and Acrobat Pro XI are installed on the same iMac with OS X 10.8.5.  How do I safely uninstall only Acrobat Pro 9 without affecting Acrobat Pro XI? When I first installed Acrobat Pro XI, I thought maybe I was suppose to leave Acro

  • Problem with GDS - FileNotFoundException

    I get the following ERROR under heavy load in the server.log when "converting" xml to pdf(generatePDFOutput). Running lc es2(cluster), jboss 4.3, suse linux 11 sp2. 2014-09-11 15:35:32,950 ERROR [com.adobe.idp.Document] DOCS001: Unexpected exception.

  • 504 error testing Push Notification

    When I run the following "Test-CsMcxPushNotification -AccessEdgeFqdn [EdgeInternalFQDN]" I get the following error: Test-CsMcxPushNotification : A 504 (Server time-out) response was received from  the network and the operation failed. See the excepti

  • Illustrator CS4 and Bridge

    You can now launch Bridge from within illustrator CS4, but how do you benefit from it? Unlike when using Photoshop, double-clicking a file opens that image in PS, what would be the workflow for using it with illustrator. I don't see a purpose.