如何使用 Java 中的键盘键按下 jButton?
How to press a jButton using keyboard key in Java?
我正在使用 jFrame 编写一个简单的计算器程序。我想用键盘按下数字而不是用鼠标点击它……我该怎么做?
My Simple Calculator
您只需将 属性 更改为 JButton,即可获得较短的路径
示例:
buttonOne.setMnemonic(KeyEvent.VK_C);
只需将关键侦听器添加到您的 class 并继承它的方法
您必须从 keylistener 方法中使用的是 keypressed 方法,只需复制我的代码和其他数字并在他按下其中一个时编写您的代码
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_1) {
//wite the code here when he pres 1
}
if (key == KeyEvent.VK_2) {
//wite the code here when he pres 2
}
if (key == KeyEvent.VK_3) {
//wite the code here when he pres 1
}
if (key == KeyEvent.VK_4) {
//wite the code here when he pres 1
}
}
我正在使用 jFrame 编写一个简单的计算器程序。我想用键盘按下数字而不是用鼠标点击它……我该怎么做? My Simple Calculator
您只需将 属性 更改为 JButton,即可获得较短的路径
示例:
buttonOne.setMnemonic(KeyEvent.VK_C);
只需将关键侦听器添加到您的 class 并继承它的方法 您必须从 keylistener 方法中使用的是 keypressed 方法,只需复制我的代码和其他数字并在他按下其中一个时编写您的代码
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_1) {
//wite the code here when he pres 1
}
if (key == KeyEvent.VK_2) {
//wite the code here when he pres 2
}
if (key == KeyEvent.VK_3) {
//wite the code here when he pres 1
}
if (key == KeyEvent.VK_4) {
//wite the code here when he pres 1
}
}