Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you simulate a full click with Java Swing?

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.

like image 561
SuperTron Avatar asked Dec 11 '11 00:12

SuperTron


3 Answers

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.

like image 125
Jonas Avatar answered Oct 18 '22 02:10

Jonas


Look into using a Robot to simulate keyboard presses and mouse activity.

  • How to use Robot
  • How to Control your Computers Mouse using the Robot class
like image 27
Nate W. Avatar answered Oct 18 '22 01:10

Nate W.


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();
            }
        });
    }
}`
like image 2
eboix Avatar answered Oct 18 '22 01:10

eboix