我通过Netbeans创建了Jform窗口,我将KeyListener添加到了类中,因此如果有人按下LEFT键,它将执行与单击按钮相同的操作。 但是在keyPressed函数中我无法调用按钮动作执行的功能。我该怎么做?
public class Main extends javax.swing.JFrame implements KeyListener{
public Main() {
//Add keyListener to the buutons (the action is defiened in fun keyPressed)
initComponents();
jButton1_Computer.addKeyListener(this);
jButton1_Student.addKeyListener(this);
}
.
.
.
private void jButton1_ComputerActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("you pressed the button");
// I want to call to this function from the keyPressed function
}
public void keyPressed(KeyEvent e) {
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_LEFT){
jButton1_ComputerActionPerformed(what kind of param should i give here?);
}
}
.
.
}
答案 0 :(得分:1)
不要调用" ActionListener"而是按下按钮上的doClick()
,然后按下按钮,这将为您调用JButton的ActionListener。
jButton1.doClick();
此外,您还需要避免使用KeyListener,而是使用Key Bindings。
答案 1 :(得分:0)
为什么不将KeyListener添加到按钮
myButton.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyPressed(KeyEvent arg0) {
}
});