Atitit. The form listens to esc to exit the form java swing c #. net php,
Atitit. Form listening to esc exit this form java swing c #. net php
1. Listen to esc key 1
1.1. Listen to a component 1
1.2. Add the listener to form 1
2. Close Form 2
1. Listen to esc buttons
1.1. Listen to a component 1.2. Listen to the form
Author: old wow's paw Attilax iron, EMAIL: 1466519819@qq.com
Reprinted please indicate Source: http://blog.csdn.net/attilax
Final Toolkit toolkit = Toolkit. getdefatooltoolkit ();
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. getdefatooltoolkit (). addAWTEventListener (new AWTEventListener (){
.............
});
This approach is best. All events are monitored. No matter which componet, button, form, etc ..
This does not work, and may focus on a component .. 3. This only event is bound to frm ..
// 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
Set this. setdefaclocloseoperation (DISPOSE_ON_CLOSE); in each Frame.
EXIT_ON_CLOSE: Close the program. (All windows and processes are closed)
DISPOSE_ON_CLOSE: close this window only.
HIDE_ON_CLOSE: only hide this window, not close.
DO_NOTHING_ON_CLOSE: Do not do anything. it is invalid to click Close.
You only need to call the dispose method. Hidden is setVisible (false ). The program to close is System. exit (0 );
Frame. setdefaclocloseoperation (javax. swing. WindowConstants. DISPOSE_ON_CLOSE );
If (evt. getKeyCode () = KeyEvent. VK_ESCAPE ){
Frame. dispose ();
// System. exit (0 );
}
Reference
Javaexample: Use a volume to close a jframe_baidu channel. htm