Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Single key Mnemonic in button in Java?

I am working on a project and I want to set Mnemonic on buttons. But the problem is Mnemonic works on pairing key example (Alt+F) etc. But I want it to be on single key.

like image 222
hemant Avatar asked Jul 07 '12 07:07

hemant


People also ask

What is mnemonic on button?

A mnemonic is an underlined alphanumeric character, typically appearing in a menu title, menu item, or the text of a button or component of the user interface. A mnemonic indicates to the user which key to press (in conjunction with the Alt key) to activate a command or navigate to a component.

What is mnemonic key in Java?

A mnemonic is a key-press that opens a JMenu or selects a MenuItem when the menu is opened. An accelerator is a key-press that selects an option within the menu without it ever being open. So, for example, if we wanted to open the Starter Menu by pressing Alt-S...we would bind a mnemonic to it.


1 Answers

  • have look at KeyBindings,

  • then you can to attach any Key to the JButton

Here is one example code for your help, just Press C on the Keyboard :

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();
            }
        });
    }
}
like image 108
mKorbel Avatar answered Sep 18 '22 15:09

mKorbel