aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Problem with KeyListener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Problem with KeyListener" Watch "Problem with KeyListener" New topic
Author

Problem with KeyListener

Alejandro Barrero
Ranch Hand

Joined: Aug 01, 2005
Posts: 311
I posted this as RESOLVED but I don't know if that worked. I used requestFocusInwindow().

I have a swing dialog with a class that extends JPanel at the center and buttons at the bottom. I use the JPanel to display the image of a JPG file. I enter strings in the image by clicking with the mouse to select a location and then I type keys. I store the strings in objects and I draw the text on the glass pane of the dialog. I can drag the strings, increase or decrease font and move them up, down, left or right with the arrow keys. For the later, I rely on a key pressed event. My problem is that when I click on a button at the bottom, the key listener stops working. I started with key listeners created with MyEclipse Matisse and later tried implementing KeyListener in the panel or the dialog, but still the listener methods are not invoked.
The listener code in the class that extends JPanel is:


I hesitate to include the the full code for the panel and the dialog because they are hundreds of lines long.


Your help will be greatly appreciated,
Alejandro Barrero
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2182
    
    7
My problem is that when I click on a button at the bottom, the key listener stops working.


KeyEvents are handled by the component that has focus. When you click on a button the button now has focus, not your panel. First of all you must use panel.setFocusable(true) to allow the panel to receive focus. Now in the ActionListener of your button you can add panel.requestFocusInWindow().

However, a better solution is to use Key Bindings. This is how Swing components handle KeyEvents.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with KeyListener