1

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.

Jump3r
  • 1,028
  • 13
  • 29
  • 1
    Don't use a null layout. Swing was designed to be using with layout managers. Read the section from the Swing tutorial on [Layout Managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). `Please explain it, don't paste links.` - we don't have time to time the contents of the tutorial. So you read the tutorial and then you can ask specific questions about something you don't understand. We can't possible guess what concept you might not understand. The tutorial also has a secton on `Key Binding` which is the proper solution to this problem. – camickr Apr 16 '15 at 17:53

1 Answers1

2

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.

Community
  • 1
  • 1
John
  • 3,769
  • 6
  • 30
  • 49
  • `I have more experience using KeyListener` - don't use a Key Listener. AWT use a KeyKistener because there was no better option. Swing was designed to be used with Key Bindings. Accelerators and mnemonics use key bindings. Don't promote old techniques. API's evolve over time for a reason. – camickr Apr 16 '15 at 17:50