【问题标题】:How do you simulate a full click with Java Swing?如何使用 Java Swing 模拟完全点击?
【发布时间】:2012-01-17 16:01:09
【问题描述】:

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

【问题讨论】:

标签: java swing keyboard actionlistener


【解决方案1】:

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

但是,如果您想分享“行动”,例如按钮和按键,您应该使用Action。见How to Use Actions

关于如何为 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);    

How to Use Key Bindings 上阅读有关键绑定的更多信息。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-02-11
        • 1970-01-01
        • 2013-10-11
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多