Atitit. Form listening ESC exit This form Java Swing C #. NET PHP
1. Monitor ESC key 1
1.1. Listening on a component 1
1.2. Monitoring added to form 1
2. Close Form 2
1. Monitor ESC Keys
1.1. Listening on a component
1.2. Listen on the form
Author:: Old Wow's paw Attilax Ayron, email:1466519819@qq.com
Final Toolkit Toolkit = Toolkit.getdefaulttoolkit ();
Toolkit.addawteventlistener (New Awteventlistener () {
@Override public void eventdispatched (AWTEvent e) {
if (e.getid () = = keyevent.key_pressed) {
KeyEvent evt = (keyevent) e;
if (evt.getkeycode () = = Keyevent.vk_escape) {
Frame.dispose ();
System.exit (0);
}
}
}
},awtevent.key_event_mask);
Java Code
Toolkit.getdefaulttoolkit (). Addawteventlistener (New Awteventlistener () {
.............
});
This is the best way. Listens for all events. No matter on which componet, Button,form and so on.
This does not work, possibly focus to one component on the bar. Three, this only event tied to a frm on the blue.
Frame.addkeylistener (New Keyadapter () {
@Override
public void keypressed (KeyEvent e) {
if (Keyevent.vk_escape = = E.getkeycode ()) {
System.exit (0);
SYSTEM.OUT.PRINTLN ("---colose ...");
Frame.dispose ();
// }
// }
// });
2. Close the form
Just set This.setdefaultcloseoperation (dispose_on_close) in each frame;
Exit_on_close, close the program. (All windows and processes will be closed)
Dispose_on_close, close this window only.
Hide_on_close, hide this window only, do not close.
Do_nothing_on_close, do nothing, click Close Invalid.
This is simple, as long as you call the Dispose method. Hide is setvisible (false). Close the program is system.exit (0);
Frame.setdefaultcloseoperation (Javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
if (evt.getkeycode () = = Keyevent.vk_escape) {
Frame.dispose ();
System.exit (0);
}
Reference
Java how to close a jframe_ by button Baidu knows. htm