Win a copy of Practice Tests for OCP Java 17 Certification Exam (1Z0-829) this week in the OCPJP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Problem with KeyListener

 
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Rancher
Posts: 3267
30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
reply
    Bookmark Topic Watch Topic
  • New Topic