比如我做了个按键1,鼠标监听的已经弄好了,我想将它和键盘上的1键建立起对应的关系啊?

解决方案 »

  1.   

    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.*;public class T
    {
    public static void main(String[] args)
    {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
    } final JTextField tf = new JTextField();
    tf.setEnabled(false);

    JPanel p = new JPanel(new GridLayout(0, 3, 5, 5));
    for (int i = 0; i <= 9; i++) {
    final JButton btn = new JButton(String.valueOf(i));
    p.add(btn);

    btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke((char)(i + '0')), "PressKeyAction");
    btn.getActionMap().put("PressKeyAction", new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    btn.doClick();
    }
    });

    btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    tf.setText(tf.getText() + btn.getText());
    }
    });
    }

    JFrame f = new JFrame();
    JComponent contentPane = (JComponent) f.getContentPane();
    contentPane.setLayout(new BorderLayout(0, 5));
    contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    f.getContentPane().add(p, BorderLayout.CENTER);
    f.getContentPane().add(tf, BorderLayout.NORTH);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    }
    }