Java listen button and keyboard click

How to press the key and trigger JButton?

For example:

I use "a" JButton as the GUI on the panel I implemented a buttonlistener on "a button", which changes the screen to something else I want to trigger this button by clicking the mouse and pressing the keyboard

How to trigger this "a" JButton by pressing "a" on the keyboard while implementing the buttonlistener?

My current code cannot trigger critical events

ButtonListener listener;
KeyboardListener keyboardListener;
private JButton aButton;

public MyButtonPanel() {
    listener = new ButtonListener();

    aButton = new JButton ("A");
    aButton.setFont (BUTTON_TEXT);
    aButton.setPreferredSize (new Dimension (60,30));
    aButton.addActionListener (listener);
    aButton.addKeyListener (keyboardListener);

    setLayout (new BorderLayout());
    add (aButton,BorderLayout.CENTER);

}

private class KeyboardListener implements KeyListener
{
    public void keyPressed(KeyEvent arg0) {
        char c = arg0.getKeyChar();
        System.out.println("Pressed " + c);
    }

    public void keyReleased(KeyEvent arg0) {
        char c = arg0.getKeyChar();
        System.out.println("Released " + c);
    }

    public void keyTyped(KeyEvent arg0) {
        char c = arg0.getKeyChar();
        System.out.println("Typed " + c);
    }

}

 private class ButtonListener implements ActionListener {
  public void actionPerformed (ActionEvent event) {
    Object source = event.getSource();

    if (source == aButton) {
        System.out.println("This is a");
    }
  }
 }

}

Solution

Create an action Then use actionlistener to add action to the button And you can handle keyboard events by binding action to keystroke

Read swing tutorial There are some contents:

>How to use actions > how to use key binding

Let you start

Or you can call the button by specifying only a mnemonic for the button Read JButton API

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>