尝试使用 Java 和 GUI 移动鼠标并单击屏幕

问题描述 投票:0回答:0

所以我试图制作一个 GUI,允许我在屏幕上移动鼠标并点击项目。希望在我为测试目的而构建的应用程序上对此进行测试。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Robot;


public class Bot implements ActionListener{
    JLabel version = new JLabel("version 2");
    JFrame window = new JFrame("Bot");
    JButton Active = new JButton("Activate");
    JButton Disable = new JButton("Disable");

    String status = "false";

    Integer number = 0;

    Bot(){
        Active.addActionListener(this);
        version.setForeground(Color.WHITE);
        Disable.setVisible(false);
        Disable.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    status = "false";
                    Active.setVisible(true);
                    Disable.setVisible(false);
                }
            }
        );

        window.add(Active);
        window.add(Disable);
        window.add(version);
        window.setLayout(new FlowLayout());
        window.getContentPane().setBackground(Color.BLACK);
        window.setSize(200,300);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
        window.setResizable(false);
    }
    public static void main(String args[]){
        Bot bot = new Bot();
    }   

    public void actionPerformed(ActionEvent e){
        status = "true";
        Active.setVisible(false);
        Disable.setVisible(true);
        try {
            counter();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
    }

    public void counter()throws AWTException{
        while(status == "true"){
            try {
                Robot r = new Robot();
                int mask = InputEvent.BUTTON1_DOWN_MASK;
                number +=1;
                System.out.println("Before");
                r.mouseMove(10, 50);
                r.mousePress(mask);
                r.mousePress(mask);
                System.out.println("After");
                System.out.println(number);
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

GUI 中的一切都可以正常工作。但是鼠标不会移动或单击。此外,单击以控制操作的按钮似乎被卡住了。

现在有些问题似乎是由于线程基本上一直处于睡眠状态。所以不确定是否更好地等待在不休眠线程的情况下在 Java 中添加延迟。

第二部分,为什么机器人/鼠标似乎没有工作,而其他一切都在工作。

java
© www.soinside.com 2019 - 2024. All rights reserved.