KeyEvent理由所有的键。到里面找就是了

解决方案 »

  1.   

    我写的一个例子,下面有解释
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class KeyTest extends JFrame {
      public KeyTest() {
          this.setSize(300,200);
          JButton btn = new JButton();
          btn.setText("Test");
          btn.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e){
                  System.out.println("CLICK");
              }
          });
          KeyStroke stroke1 = KeyStroke.getKeyStroke(KeyEvent.VK_F,ActionEvent.CTRL_MASK,true);
          btn.registerKeyboardAction(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    System.out.println("OK");
                }
            },stroke1,JComponent.WHEN_FOCUSED);
          this.getContentPane().add(btn);  }
      public static void main(String[] args) {
        KeyTest keyTest1 = new KeyTest();
        keyTest1.show();
      }
    }
    首先引入包
    import javax.swing.event.*;
    然后定义一个
        KeyStroke stroke1 = KeyStroke.getKeyStroke     (KeyEvent.VK_F,ActionEvent.CTRL_MASK,true);//创建一个KeyStroke类
        最后一个参数的意思是是否在Keyrelease时触发此事件
       btn.registerKeyboardAction(new ActionListener(){
                //要执行的方法
                public void actionPerformed(ActionEvent e){
                    System.out.println("OK");
                }
            },stroke1,JComponent.WHEN_IN_FOCUSED_WINDOW);
        }
        registerKeyboardAction方法的参数意思是这样的
        1.ActionListener对象,可以定义你要执行的方法
        2.KeyStroke 对象,定义触发事件的条件
        3.何时按Ctrl+Enter时发生此事件,比如
            JComponent.WHEN_IN_FOCUSED_WINDOW
            JComponent.WHEN_FOCUSED等