简体   繁体   中英

How to make JButton react to keypressed method?

I'm using JFrame Form in Netbeans to make a simple Piano game and i'd like to be able to control JButtons using computer keyboard keys. When I want to use ActionPerformed method and keypressed in Design options it only let me to control the button that I previously clicked with the mouse. Other buttons do not react. I've tried to solve it by making keypressed writing it myself, but in this case nothing happens when I'm pushing keyboard keys.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String soundName = "C.wav";
    AudioInputStream audioInputStream = null;
    try {
        audioInputStream = AudioSystem.getAudioInputStream(new
                File(soundName).getAbsoluteFile());
    } catch (UnsupportedAudioFileException | IOException ex) {
        Logger.getLogger(GameWindow.class.getName()).log(Level.SEVERE, null, ex);
    }
    Clip clip = null;
    try {
        clip = AudioSystem.getClip();
    } catch (LineUnavailableException ex) {
        Logger.getLogger(GameWindow.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        clip.open(audioInputStream);
    } catch (LineUnavailableException | IOException ex) {
        Logger.getLogger(GameWindow.class.getName()).log(Level.SEVERE, null, ex);
    }
    clip.start();
}
public void keyPressed(KeyEvent evt){
    int keyCode = evt.getKeyCode();
    if (keyCode == KeyEvent.VK_Z) {
        jButton1.getModel().isPressed();
    }
    if (keyCode == KeyEvent.VK_S) {
        jButton2.getModel().isPressed();
    }
}

You can use Swing key bindings to achieve this. Try below example. Use of InputMap and ActionMap is the highlight of this example.

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

public class ClickButtonsThroughKeyboard
{
  private static Action buttonOneClickAction = new ButtonOneClickAction();
  private static Action buttonTwoClickAction = new ButtonTwoClickAction();

  public static void main(String[] args)
  {
    JButton button1 = new JButton("One");
    button1.addActionListener(buttonOneClickAction);

    button1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('z'), "z_typed");
    button1.getActionMap().put("z_typed", buttonOneClickAction);

    JButton button2 = new JButton("Two");
    button2.addActionListener(buttonTwoClickAction);

    button2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('s'), "s_typed");
    button2.getActionMap().put("s_typed", buttonTwoClickAction);

    JFrame f = new JFrame("Click Button Programmatically");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(button1);
    f.getContentPane().add(button2);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

class ButtonOneClickAction extends AbstractAction
{
  @Override
  public void actionPerformed(ActionEvent e)
  {
    System.out.println("Button One clicked");
  }
}

class ButtonTwoClickAction extends AbstractAction
{
  @Override
  public void actionPerformed(ActionEvent e)
  {
    System.out.println("Button Two clicked");
  }
}

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