0

I basically want to be able to press a JButton by pressing a Key on my Keyboard. For example:

If I press "T", it should use the JButton "Testing". If I press "H", it should use the JButton "Hello" and so on...

which is the easiest (and laziest) way to do this?

1 Answers1

-1

Set mnemonic char on that button

JButton btnTesting = new JButton("Testing");
btnTesting.setMnemonic('T');

You will use it by pressing alt+T in this case.

EDIT

To reproduce this function without ALT key you will have to use KeyListener that you register on container holding your buttons. You will have to implement logic that determines which key corresponds to which button.

Sample:

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

    public class ButtonPressDemo {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    initGUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static void initGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 300, 300);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        // add your buttons
        contentPane.add(new JButton("A"));
        contentPane.add(new JButton("B"));
        contentPane.add(new JButton("C"));

        contentPane.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                int keyPressed = e.getKeyCode();
                System.out.println("pressed key: "+keyPressed);
                // do something ...
            }
        });
        contentPane.setFocusable(true); // panel with keyListener must be focusable
        frame.setContentPane(contentPane);
        contentPane.requestFocusInWindow(); // panel with key listener must have focus
        frame.setVisible(true);
    }
}

With this approach your GUI will not react visually to pressing the mnemonic key i.e. buttons will not animate as they would with the setMnemonic and the mnemonic char will not be automatically underlined in label of the button.

MatheM
  • 801
  • 7
  • 17
  • Is there no way to do it without "alt"? –  Jun 07 '16 at 11:51
  • You would have to register key listener on panel that holds your buttons get character that was typed and determine which button it represents. – MatheM Jun 07 '16 at 12:07