I am implementing some keyboard code for an existing java swing application, but I can't seem to get a keyboard press to execute the "mousePressed" action and "mouseReleased" action that are mapped to a JButton. I have no problems clicking it for the "action_performed" with button.doClick(), is there a similar function for simulating the mouse presses? Thanks beforehand.
You can simulate mouse presses and mouse actions by using the Robot class. It's made for simulation e.g. for automatically test user interfaces.
But if you want to share "actions" for e.g. buttons and keypresses, you should use an Action
. See How to Use Actions.
Example on how to share an action for a Button and a Keypress:
Action myAction = new AbstractAction("Some action") {
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
};
// use the action on a button
JButton myButton = new JButton(myAction);
// use the same action for a keypress
myComponent.getInputMap().put(KeyStroke.getKeyStroke("F2"), "doSomething");
myComponent.getActionMap().put("doSomething", myAction);
Read more about Key-bindings on How to Use Key Bindings.
Look into using a Robot
to simulate keyboard presses and mouse activity.
You could add a listener to your button:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonAction {
private static void createAndShowGUI() {
JFrame frame1 = new JFrame("JAVA");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton(" >> JavaProgrammingForums.com <<");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With