简体   繁体   中英

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.

You can simulate mouse presses and mouse actions by using the Robot class. It's made for simulation eg for automatically test user interfaces.

But if you want to share "actions" for eg 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();
            }
        });
    }
}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM