我需要一些帮助来为下一个示例中的按钮添加 keylistener 或键绑定。我希望当我在键盘上按下 A 或 B 时,做出与用鼠标按下时相同的动作。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class NetTest {
static JButton btnA = new JButton("A");
static JButton btnB = new JButton("B");
static JPanel jp = new JPanel();
static JFrame jf = new JFrame("Test APP");
static JLabel jl = new JLabel("Which button was clicked ?");
static ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
jl.setText(((JButton)e.getSource()).getText());
}
};
public static void main(String[] args) {
jf.setVisible(true);
jf.setSize(400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp.add(btnA);
jp.add(btnB);
jp.add(jl);
jf.add(jp);
btnA.addActionListener(action);
btnB.addActionListener(action);
}
}