JAVA JButton快捷键设置(组合键+单键)

快捷键:
1、这种设置不适合之处就是一定要加上一个Alt键才行,JMenu,JButton都可用
jButton.setMnemonic(KeyEvent.VK_ENTER); 
这是一种较简单的,快捷键是按Alt+enter回车键。 


2、若是设置类似“Ctrl+某键”的快捷键方式,JButton不可用,可以直接: 

jMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R , KeyEvent.CTRL_MASK))


3、单键设置

jButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),JComponent.WHEN_IN_FOCUSED_WINDOW);


以下单键例子:

按钮:

login = new JButton("登录");
login.registerKeyboardAction(this, 
   KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),JComponent.WHEN_IN_FOCUSED_WINDOW);
exit = new JButton("关闭");
exit.registerKeyboardAction(this, 
   KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_IN_FOCUSED_WINDOW);

login.addActionListener(this);
exit.addActionListener(this);

事件:

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
 Object obj = e.getSource();
       if(obj == login)   { 

 
                 else if(obj == exit){ 
             System.exit(0);
                }else{
               }

}

你可能感兴趣的:(JAVA)