繁体   English   中英

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

[英]How do you simulate a full click with Java Swing?

我正在为现有的java swing应用程序实现一些键盘代码,但我似乎无法通过键盘按下来执行映射到JButton的“mousePressed”动作和“mouseReleased”动作。 使用button.doClick()点击“action_performed”没有问题,是否有类似的功能来模拟鼠标按下? 先谢谢。

您可以使用Robot模拟鼠标按下和鼠标操作。 它用于模拟,例如用于自动测试用户界面。

但是如果你想分享按钮和按键的“动作”,你应该使用Action 请参见如何使用操作

有关如何共享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);    

阅读有关如何使用键绑定的键绑定的更多信息

考虑使用Robot来模拟键盘按下和鼠标活动。

您可以为按钮添加一个监听器:

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