I just started using java and am not very good, so if you could help me that would be awesome! I'm making a Swing
application and want to close it only when a certain key is pressed. Is there a way to do this?

- 41
- 1
- 1
- 2
-
Don't use a KeyListener that is an old AWT solution (I really should downvote all those suggestions). Swing was designed to be used with Key Bindings. – camickr Aug 09 '11 at 19:20
-
Do you care about the close button in the frame decorations? Both key listener and bindings are shown [here](http://stackoverflow.com/questions/6887296). – trashgod Aug 09 '11 at 21:51
5 Answers
Going against the other X answers here, I'm going to recommend that you not use a KeyListener but rather use key bindings. This is a higher level abstraction, and helps you avoid focus issues that come with use of KeyListeners. You can find out more about key bindings in the Swing tutorials here: How to use Key Bindings

- 283,665
- 25
- 256
- 373
When you want a program to react immediately once a key is pressed, you use keyboard events and the KeyListener
interface. Unlike the ActionListener
or ItemListener
interfaces, the KeyListener
interface must implement three methods:
void keyPressed(KeyEvent)
-- A method called the moment a key is pressedvoid keyReleased(KeyEvent)
-- A method called the moment a key is releasedvoid keyTyped(KeyEvent)
-- A method called after a key has been pressed and released
Although all of these methods must be present in your code, you don't have to have any statements inside of them.
Call the getKeyChar()
method to find out which key was pressed. As the method implies, this is returned as a char
value. However, this method only works for letter keys, number keys, and punctuation keys.
To monitor any key on the keyboard, use the getKeyCode()
method. This is returned as an int
value. You can follow that up with a getKeyText()
method, with the int
value as the argument. This will return the actual name of the key (i.e. Home, F2, etc.).
You want a window to close only when a certain key is pressed. Below is an example of how you would go about doing that:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class example extends JFrame implements KeyListener {
JLabel closeLabel = new JLabel("Press the \"x\" key to close me!");
public example() {
super("Close me!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
closeLabel.addKeyListener(this);
closeLabel.setFocusable(true);
add(closeLabel);
pack();
setVisible(true);
}
public void keyTyped(KeyEvent input) {
char key = input.getKeyChar();
if (key == 'x') System.exit(0);
}
public void keyPressed(KeyEvent txt) {
//do nothing
}
public void keyReleased(KeyEvent txt) {
//do nothing
}
}

- 6,298
- 2
- 30
- 46
-
your approach requires `closeLabel` to have focus, right? How do you add support for the entire window, and not allow any control to hide the keypress? – Dilum Ranatunga Aug 09 '11 at 17:37
-
@Dilium You have to add a `KeyListener` to every component in your frame. Also, some components aren't focusable (like `JLabel`). You have to do `someComponent.setFocusable(true);` – fireshadow52 Aug 09 '11 at 17:41
-
3To avoid focus problems don't use a KeyListener but rather use key bindings instead. – Hovercraft Full Of Eels Aug 09 '11 at 18:28
-
@Hovercraft Full of Eels +1 to that, but I wanted to suggest something relatively simple for the OP. – fireshadow52 Aug 09 '11 at 19:13
-
-1, This is not a simple solution. Adding the KeyListener to every component is a terrible solution, especially as the complexity and number of components grows on the frame. Also there is no reason to make the label components focusable, since some other component would have focus. – camickr Aug 09 '11 at 19:38
-
@camickr Which other component? There is only one component. Har har I know what you mean. But yeah, Key Bindings is better. – fireshadow52 Aug 09 '11 at 19:44
-
@Tony You should go with Hovercraft Full Of Eels's answer. It's the better way to do this. – fireshadow52 Aug 09 '11 at 19:51
-
You people and your ridiculous elitism. How about actually WRITTING SOME CODE EXAMPLES ABOUT KEY BINDINGS, instead of telling off all the time. I've come to 4 seperate questions by now on this sort of subject and its always some people actually posting code examples (in regards to Key Listeners), and some others doing nothing other than telling them off and downvoting, calling on Key Bindings to be used instead while not giving one line of example code. I still have no idea how to use these stupid key bindings. – flamming_python Jun 11 '13 at 17:13
-
@flamming_python Well, in their defense, after reading up about Key Bindings and comparing it to KeyListeners, I realized that Key Bindings is infinitely easier to use, and the risk of error is lesser than using KeyListeners. I just made the mistake of not being quite up to date on the latest APIs. As for showing code, yes, that would be very helpful, but what good is that if the asker of the question doesn't know a thing about Key Bindings? It may satisfy the OP, but as a wise man once said, "*Give a man a fish and he'll eat for a day; teach a man to fish and he'll eat for a lifetime...*" – fireshadow52 Jun 13 '13 at 05:48
You have to take a look at the KeyListener
interface, and i suggest you read this kind of article that explain clearly the swing way of doing things, here

- 13,885
- 7
- 36
- 56
-
+1 The comment about the KeyLIstener is wrong since the Swing way of doing things has nothing to do with a KeyListener. However, I do like the link to the Swing tutorial on Using Menus. This is the easy way to use Key Bindings since the creation of the menu items with create the bindings for you automatically. Using menus also gives you the benefit of self documenting the key strokes that can be used in your program. – camickr Aug 09 '11 at 19:24
Add a KeyListener
and check if your key was pressed. Here's a tutorial on how to do that. http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html

- 56,312
- 72
- 233
- 406
you must register an handler to handle keypressed on the swing component you want to react. On the handler, close the window.
This is the observer pattern http://www.javaworld.com/javaworld/javaqa/2001-05/04-qa-0525-observer.html

- 8,103
- 12
- 53
- 106