|
|
获取"Escape"事件
原文:http://www.devx.com/tips/Tip/28271?trk=DXRSS_JAVA 翻译:ZhangV
考虑这样一种情况,当一个对话框(dialog)由一个面板(panel)启动,而这个面板自身又是由另一个panel启动.当ESCAPE键按下时对话框也被关闭是件很烦人的事.下面的代码可以容易地获得ESCAPE键盘事件,执行指定的动作而不需要考虑层次.
-
- //Has to be final because this instance is required in the inner class
- final UpdateCustomerData updationPanel = new UpdateCustomerData
-
- (mainPanel);
- //Setting the size
- updationPanel.setSize(400,150);
- //Creating an input map of the Root Pane
- InputMap map = updationPanel.getRootPane().getInputMap(
- JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
- //Adding the key that needs to be captured
- map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel" );
- ActionMap actionMap = updationPanel.getRootPane().getActionMap();
- //Creating the action that needs to be executed when the key is pressed
- Action close = new AbstractAction() {
- public void actionPerformed(ActionEvent ae)
- {
- updationPanel.dispose();
- }
- };
- actionMap.put( "cancel", close);
- //Displaying the Panel
- updationPanel.setVisible(true);
updatePanel是一个会被ESCAPE键事件影响的面板 |
|