我有一个简单JButton
的方法链接actionPerformed
。现在我想将一个键绑定到按钮上,这样当我在键盘上按下这个键时,它会执行与用鼠标按下按钮相同的操作。
我发现这段代码正在工作,但正如你所见,当按下键或按下按钮时,我必须编写两次代码才能执行。
有没有办法避免这种情况?
import java.io.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.*;
public class provakey implements ActionListener{
private JButton bStart;
//Costruttore
public provakey() throws IOException{
initGUI();
}
private void initGUI(){
JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel();
bStart = new JButton("Avvia");
bStart.addActionListener(this);
bStart.setActionCommand("start");
bStart.setBounds(140,10,150,40);
AbstractAction buttonPressed = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (bStart.isEnabled()){
System.out.println("pressed");
}
}
};
bStart.getActionMap().put("start", buttonPressed);
bStart.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,0), "start");
buttonPanel.setLayout(null);
buttonPanel.setBounds(0,240,600,60);
buttonPanel.add(bStart);
frame.setLayout(null);
frame.add(buttonPanel);
frame.setTitle("Prova");
frame.setSize(600, 350);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if ("start".equals(e.getActionCommand())) {
buttonPressed();
}
}
public void buttonPressed(){
System.out.println("pressed");
}
public static void main (String args[]) throws IOException {
provakey p = new provakey();
}
}