简体   繁体   English

如何用Java Swing模拟完整点击?

[英]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. 我正在为现有的java swing应用程序实现一些键盘代码,但我似乎无法通过键盘按下来执行映射到JButton的“mousePressed”动作和“mouseReleased”动作。 I have no problems clicking it for the "action_performed" with button.doClick(), is there a similar function for simulating the mouse presses? 使用button.doClick()点击“action_performed”没有问题,是否有类似的功能来模拟鼠标按下? Thanks beforehand. 先谢谢。

You can simulate mouse presses and mouse actions by using the Robot class. 您可以使用Robot模拟鼠标按下和鼠标操作。 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 . 但是如果你想分享按钮和按键的“动作”,你应该使用Action See How to Use Actions . 请参见如何使用操作

Example on how to share an action for a Button and a Keypress: 有关如何共享Button和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. 考虑使用Robot来模拟键盘按下和鼠标活动。

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();
            }
        });
    }
}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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