键盘驱动组件事件

来源:互联网 发布:希尔伯特矩阵的逆 编辑:程序博客网 时间:2024/06/05 07:59

如何利用键盘驱动组件事件???

1:使用组件提供的getInputMap()返回一个InputMap对象,

   该对象用于将KeyStroke对象(代 表键盘或者其他的输入事件)和名字关联起来;

2:使用组件的getActionMap()返回一个ActionMap对象,

   该对象用于将指定的名字与事件Actioc联系起来ActionActionListener的子接口)


 

1:jtf.getInputMap().put(keyStrokename);

2jtf.getActionMap().put(name, action);

Demo1

public class BindKey extends JFrame {JTextArea jta=new JTextArea(5,30);JButton btn=new JButton("发送");JTextField jtf=new JTextField(15);public BindKey(){this.add(jta);JPanel jp=new JPanel();jp.add(jtf);jp.add(btn);this.add(jp,BorderLayout.SOUTH);/** * Action是ActionListener的子接口 */Action sentMsg=new AbstractAction() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjta.append(jtf.getText()+"\n");jtf.setText("");}};btn.addActionListener(sentMsg);//jtf.getInputMap().put(keyStroke, name);jtf.getInputMap().put(KeyStroke.getKeyStroke('\n', java.awt.event.InputEvent.CTRL_MASK), "send");///jtf.getActionMap().put(name, action);jtf.getActionMap().put("send",sentMsg);this.pack();this.setTitle("键盘与事件的绑定");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubBindKey b=new BindKey();}}


0 0
原创粉丝点击