如何利用键盘驱动组件事件???
1:使用组件提供的getInputMap()返回一个InputMap对象,
该对象用于将KeyStroke对象(代
表键盘或者其他的输入事件)和名字关联起来;
2:使用组件的getActionMap()返回一个ActionMap对象,
该对象用于将指定的名字与事件Actioc联系起来(Action是ActionListener的子接口)
1:jtf.getInputMap().put(keyStroke, name);
2:jtf.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() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jta.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 stub BindKey b=new BindKey(); } }