tags:

views:

367

answers:

3

hi i'm 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've tried a lot to solve it but all in vain so any help regarding this will be appreciated. thanks.

this is my keyListener

_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
  }   
};
+1  A: 

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

// 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);

http://helpdesk.objects.com.au/java/how-to-specify-a-hot-key-for-a-swing-application

objects
How about an answer, rather than a link?
Tom Hawtin - tackline
the link contains the example code that shows how to do what I have suggested, ie. add a hot ket instead of using a key listener
objects
thanks for your reply HotKey works as per my expectations.
gopal
+1  A: 

You would need to add the key listener to exactly the component that has focus (many components are actually composites).

So use JComponent.registerKeyboardAction with a condition of WHEN_IN_FOCUSED_WINDOW. Alternatively use JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW, true) and JComponent.getActionMap(true) as described in the registerKeyboardAction API docs.

Tom Hawtin - tackline
thanks for your reply Tom the issue is solved.
gopal
A: 

Please check whether a runtime exception is thrown. may be you are in the wrong thread for showing this dialog or another issue could throw this exception.

Also please think about to use a asynch thread for showing your dialog instead of using the listener thread. But this is just a think about.

Markus Lausberg
i didn't get your reply!i was dealing with Key press event not any multi threading issue. and anyway problem is solved.
gopal