首页 > 代码库 > How to set a decorate key

How to set a decorate key

 1 import java.awt.event.InputEvent; 2  3 import javax.swing.KeyStroke; 4  5 /** 6  * class KeyEvent: include many static key  7  * class KeyStroke: generate machine recognition key  8  * */ 9 /**10  * How To Set a decorate key ?11  * Must transform  string key  to machine  recognition language 12  * The machine can recognition key is keyStroke type 13  * getKeyStroke() method will generate a keystroke by character and a key by askII 14  * one ASC values  stand for one key on the keyboarder15  * when we want to give a menu item a decorate key ,just use method setAccelerator()16  * this parameter is what key  we want to set .   17  * */18 import javax.swing.*;19 import java.awt.event.*; 20 public class TestKey extends JFrame{21 22     public void launch(){23         JMenuBar mb = new JMenuBar();24         JMenu test = new JMenu("Test");25         JMenuItem mi1 = new JMenuItem("Test1");26         JMenuItem mi2 = new JMenuItem("Test1");27         mi1.addActionListener(new ActionListener(){28             @Override29             public void actionPerformed(ActionEvent e ){30                 31                 System.out.println(e.getSource()+"->>Pressed");32             }33             34         });35         mi2.addActionListener(new ActionListener(){36             @Override37             public void actionPerformed(ActionEvent e ){38                 39                 System.out.println(e.getSource()+"->>Pressed");40             }41             42         });43         mi1.setAccelerator(KeyStroke.getKeyStroke(‘V‘, InputEvent.CTRL_MASK));44         mi2.setAccelerator(KeyStroke.getKeyStroke((char)KeyEvent.VK_DELETE));45         46         test.add(mi1);47         test.add(mi2);48         mb.add(test);49         this.setJMenuBar(mb);50         setBounds(500,200,300,300);51         setVisible(true);52         53     }54     public static void main(String[] args) {55         TestKey t = new TestKey();56         t.launch();57 58     }59 60 }