Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

Close a JFrame with the ESC key

Thread view: 
Allan Valeriano - 02 Mar 2007 15:22 GMT
Hi,

I have this class that extends JFrame, and I'd like to close it when
the user presses the ESC key.
I've tryed the code:

   addKeyListener(new KeyListener() {
     public void keyPressed(KeyEvent e) {
     }
     public void keyReleased(KeyEvent e) {
       if (e.getKeyCode() == 27){
         System.out.println("closing...");
         close();
       }
     }
     public void keyTyped(KeyEvent e) {
     }
   });

but it seems useless, since there's no output when the ESC key is
pressed.
Anybody knows how to do that?

thanks in advance
Allan Valeriano
Jason Cavett - 02 Mar 2007 16:02 GMT
> Hi,
>
[quoted text clipped - 21 lines]
> thanks in advance
> Allan Valeriano

While I don't know if this is your problem, you should use
KeyEvent.VK_ESCAPE instead of 27.  IIRC, 27 will not necessarily
always map to the same value on a keyboard if the keyboard is for a
different language.

Also, within your code, what object are you adding that key event to?
For example, assuming you are implementing that method inside the
JFrame in question, you should have...

   this.addKeyListener(new KeyListener() {
     public void keyPressed(KeyEvent e) {
     }
     public void keyReleased(KeyEvent e) {
       if (e.getKeyCode() == 27){
         System.out.println("closing...");
         close();
       }
     }
     public void keyTyped(KeyEvent e) {
     }
   });

(Notie the "this" reference on the first line.)

Just wanted to clarify to weed out any minor issues first.
Tom Hawtin - 02 Mar 2007 22:16 GMT
> I have this class that extends JFrame, and I'd like to close it when
> the user presses the ESC key.

>     addKeyListener(new KeyListener() {

It's a really poor idea to needlessly extend classes. I know there is
lots of bad tutorial code out there that inappropriately inherit, but it
is really quite poor design.

>       public void keyPressed(KeyEvent e) {
>       }
>       public void keyReleased(KeyEvent e) {

keyTyped would be more conventional.

>         if (e.getKeyCode() == 27){

> but it seems useless, since there's no output when the ESC key is
> pressed.

Do any other keys call that method?

Key events are fired for a single component. So if the focus is in a
text field, the enclosing frame will not receive the event (nor would an
enclosing JComboBox, incidentally).

The magic parts of the APIs are:

    JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW)
    JComponent.getActionMap()

(If you want to see how it's used, look at the docs for
JComponent.registerKeyboardAction(ActionListener,String,KeyStroke,int),
which was the old, easier-to-use way of doing it.)

Tom Hawtin
blmblm@myrealbox.com - 03 Mar 2007 21:16 GMT
> > I have this class that extends JFrame, and I'd like to close it when
> > the user presses the ESC key.
[quoted text clipped - 4 lines]
> lots of bad tutorial code out there that inappropriately inherit, but it
> is really quite poor design.

Your objection is to extending JFrame, right?  I ask because the
placement of your comment made me think initially that you were
objecting to the anonymous inner class, which seems completely
reasonable and even idiomatic.  Just checking!

> >       public void keyPressed(KeyEvent e) {
> >       }
> >       public void keyReleased(KeyEvent e) {
>
> keyTyped would be more conventional.

But would it work here?  My understanding is that KeyTyped events
are generated only for Unicode characters ....

I started to type "but I'm too slack to try it", but really, how
long would it take to write a simple test program.

My test program suggests that keyTyped is invoked when the
ESC key is pressed (huh!), but the character you get (result of
calling getKeyChar on the event passed to keyTyped) appears to be
KeyEvent.CHAR_UNDEFINED.  And the API says that calling getKeyCode
in keyTyped isn't guaranteed to produce meaningful results.  So this
may not be the way to go.

I agree, by the way, that the OP's problem may be with which component
has the keyboard focus.

> >         if (e.getKeyCode() == 27){
>
[quoted text clipped - 15 lines]
> JComponent.registerKeyboardAction(ActionListener,String,KeyStroke,int),
> which was the old, easier-to-use way of doing it.)

Signature

B. L. Massingill
ObDisclaimer:  I don't speak for my employers; they return the favor.

Allan Valeriano - 04 Mar 2007 15:12 GMT
> Hi,
>
[quoted text clipped - 21 lines]
> thanks in advance
> Allan Valeriano

Nevermind.
I found this solution, and it's working fine. Thanks anyway.

KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,
0, false);
Action escapeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//close the frame
}
};
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke,
"ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escapeAction);


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.