如何在Java中的按钮中设置单键助记符?

时间:2012-07-07 07:20:30

标签: java swing jbutton key-bindings

我正在开发一个项目,我想在按钮上设置助记符。但问题是助记符在配对关键示例( Alt + F )等方面起作用。但我希望它在单键上。

1 个答案:

答案 0 :(得分:7)

  • 看看KeyBindings,

  • 然后您可以将任何密钥附加到JButton

以下是一个示例代码供您使用,只需在键盘上按 C

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Action;

public class ButtonExample
{
    private JFrame frame;
    private JButton button;

    private void displayGUI()
    {
        frame = new JFrame("Button Mnemonic Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();      
        Action buttonAction = new ButtonAction("CLICK ME"
                                , "This is a Click Me JButton");
        button = new JButton(buttonAction);                                             
        button.getInputMap().put(KeyStroke.getKeyStroke('c'), "Click Me Button");
        button.getActionMap().put("Click Me Button", buttonAction);

        contentPane.add(button);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    class ButtonAction extends AbstractAction
    {
        public ButtonAction(String text, String desc)
        {
            super(text);
            putValue(SHORT_DESCRIPTION, desc);
        }

        @Override
        public void actionPerformed(ActionEvent ae)
        {
            JOptionPane.showMessageDialog(frame, "BINGO, you SAW me.");
        }
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ButtonExample().displayGUI();
            }
        });
    }
}