File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes how to close window with return key Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "how to close window with return key" Watch "how to close window with return key" New topic

how to close window with return key

Isaac Jones

Joined: Jun 18, 2004
Posts: 25
hi everyone

i'm trying to close a window with a close-button when hitting the return key of my keyboard. but when hitting the key the only thing that happens is that the button gets selected (i've set it as default button). i've put a keylistener to my close button. does anyone know how to do that?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46397
KeyListeners on buttons? Hardly standard practice. You ought to use what they call "high-level" listeners on buttons, eg ActionListeners.

If you are still planning to use a KeyListener, you have to make sure it can receive the focus, add a KeyListener to it, then get a KeyEvent and get the (int) type of key from that KeyEvent, then if it is the type you want, set off the action.

Before you do that, try your app again, and instead of an enter key, try the space bar.


[edit]I trust you have read about KeyListeners in the Java Tutorial?[/edit]
[ August 16, 2006: Message edited by: Campbell Ritchie ]
Isaac Jones

Joined: Jun 18, 2004
Posts: 25

thanks for your answer. well it actually works with any other key. if set the close button as default button, meaning when i hit the return key the button gets selected but nothing happens. even when i hit enter again. but when i press any other key while the button is selected the window closes. i don't really understand why it it like that. do i have to treat the return-key special?

Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> (i've set it as default button)

how? post your code.

works OK in this
Isaac Jones

Joined: Jun 18, 2004
Posts: 25
i'm sorry, i'm talking about swt here, looks like you're talking about swing. maybe it works the same. this is what i have so far:

the do_login(e)-Method doesdn't do much yet. just closes the loginwindow as follows:

any ideas?
I agree. Here's the link:
subject: how to close window with return key
jQuery in Action, 3rd edition