Hot Key Instead Of Key Listener

Problem:

I am using swing and in my main frame(JFrame).  I want that when ever user press + key one window lets say test should appear. My key listener works fine if I don't call the show method of the newly added JInternalFrame but when I call the show method of my JInternalFrame the KeyListener stops listening any more.

I have tried a lot to solve it but all in vain.

This is my keyListener:

Code:

    _mainFrameKeyListener = new KeyListener()
  {
   public void keyPressed(KeyEvent arg0) {
    // TODO Auto-generated method stub
    System.out.println("the key pressed Id is : " + arg0.getKeyCode());

    if(arg0.getKeyCode() == 107){
     test Test = new test();
     _mainDesktopPane.add(Test);
     Test.show();

    }
   }
   public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub
   }

   public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub
   } 
    };
 

Answer:

Sounds like you want a hot key instead of a key listener to avoid focus issues.

Code:

    // Get the KeyStroke for our hot key

    KeyStroke plus = KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0, true);

    // Get the input map for our component
    // In this case we are interested in key strokes in the focussed window

    InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

    // Map the key stroke to our "action key" (see below)

    inputMap.put(plus, "my_action");

    // Get the action map for our component

    ActionMap actionMap = panel.getActionMap();

    // Add the required action listener to out action map

    actionMap.put("my_action", actionListener);

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.