简体   繁体   中英

Java JButton shortcut

I know how to use accelerators and mnemonics, but not "true" hotkeys.

Can someone explain me, step by step, how it works?

I want to add hotkey "1" to JButton (on numeric too(is there any difference between them?))

  1. It'll call actionPerformed? Or I can call my own function?
  2. What with other objects(JMenuItem, JCheckbox, JCombobox)?

This is base code that I'm using:

JButton b1 = new JButton("1");
setLayout(null);
b1.setBounds(0,0,50,50);
b1.addActionListener(this);
add(b1);

Please explain it, don't paste links. Thanks in advance.

You should look into KeyListener , or the much better solution KeyBindings . Basically here is what you need:

KeyListener listener = new KeyListener()
{
    public void keyReleased(KeyEvent e)
    public void keyTyped(KeyEvent e){}
    public void keyPressed(KeyEvent e)
    {
        switch(e.getKeyCode())
        {
        case KeyEvent.VK_1:
            jbutton.doClick();
            break;
            // Add other key presses here. VK_2 -> 2, VK_3 -> 3, ect.
        default:
            // A key was pressed that you were not prepared to handle.
            break;
        }
    }
};

I have more experience using KeyListener so that is what I used in my example. This KeyListener should be added to your component that is currently in focus, like this:

jpanel.addKeyListener(listener)

Remember that the KeyListener must be added to the component that is currently in focus. Depending on your layout, this may not be a JPanel .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM