我想在一个窗口上按F1弹出一个帮助对话框,响应事件,怎么办啊?
晕啊

解决方案 »

  1.   

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;import javax.swing.*;public class HelpDlgTest
    {
    public static void main(String[] args)
    {
    JPanel p = new JPanel();
    p.add(new JButton("Test"));
    p.add(new JButton("Hello"));
    p.add(new JCheckBox("CheckBox"));

    final JFrame f = new JFrame("Test");
    f.getContentPane().add(p, BorderLayout.CENTER);
    f.setSize(400, 300);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JDialog helpDlg = new JDialog(f, "Help", false);
    helpDlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    helpDlg.setSize(200, 200);
    final JTextArea ta = new JTextArea();
    ta.setLineWrap(true);
    JScrollPane sp = new JScrollPane(ta);
    helpDlg.getContentPane().add(sp, BorderLayout.CENTER);

    Action helpAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    Component comp = f.getFocusOwner();
    if (comp != null && comp instanceof AbstractButton) {
    ta.setText("当前获得焦点的组件是: " + ((AbstractButton) comp).getText());
    if (helpDlg.isVisible() == false) {
    helpDlg.setLocationRelativeTo(f);
    helpDlg.setVisible(true);
    }
    }
    }
    };
    f.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "Help");
    f.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0), "Help");
    f.getRootPane().getActionMap().put("Help", helpAction);

    f.setVisible(true);
    }
    }