Reputation: 53
I created Jform windows via Netbeans , i added KeyListener to the class so if someone press LEFT key it will do the same action as clicking on the button. but in the keyPressed function i can not call to the button action performed function . how can i do it?
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?);
}
}
.
.
}
Upvotes: 0
Views: 544
Reputation: 285405
Don't call the "ActionListener", instead, call doClick()
on the button which will press the button, and that will call the JButton's ActionListener for you.
jButton1.doClick();
Also you will want to avoid using KeyListener for this and instead use Key Bindings.
Upvotes: 1
Reputation: 763
Why dont you add KeyListener to button
myButton.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyPressed(KeyEvent arg0) {
}
});
Upvotes: 0