温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java如何实现鼠标随机移动效果

发布时间:2022-05-19 16:47:04 来源:亿速云 阅读:222 作者:iii 栏目:开发技术

这篇文章主要介绍“Java如何实现鼠标随机移动效果”,在日常操作中,相信很多人在Java如何实现鼠标随机移动效果问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Java如何实现鼠标随机移动效果”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

实现代码

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

/**
 * Java实现鼠标随机移动
 */
public class MouseController implements Runnable {

    private Robot robot;
    private boolean isStop = false;

    public MouseController() {
        try {
            ControllerFrame frame = new ControllerFrame("Prevent Locking");
            frame.setVisible(true);
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        int x;
        int y;
        Random random = new Random();
        while (!isStop) {
            //随机生成坐标。
            x = random.nextInt(1000);
            y = random.nextInt(1000);
            //开始移动
            robot.mouseMove(x, y);
            //每5秒移动一次
            robot.delay(6000);
        }

    }

    /**
     * GUI Frame 生成一个button,控制程序
     *
     * @author max
     */
    private class ControllerFrame extends JFrame {
        private static final long serialVersionUID = 1L;

        private JButton close = new JButton("close");

        public ControllerFrame(String title) {
            this();
            setTitle(title);
        }

        public ControllerFrame() {
            setLayout(new FlowLayout(FlowLayout.LEADING));
            setSize(100, 100);
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);

            Dimension preferredSize = new Dimension(100, 60);
            Font font = new Font("", 1, 14);

            //设置button 大小,文字等属性
            close.setPreferredSize(preferredSize);
            close.setFont(font);
            close.setBorderPainted(true);
            close.setFocusable(false);

            add(close);

            //点击button后,程序终止。
            close.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isStop = true;
                    dispose();
                }
            });

        }

    }

    public static void main(String[] args) {
        MouseController m = new MouseController();
        m.run();
    }

}

效果图

运行后会弹出一个框,然后你就切换到会过期的应用窗口就行了

Java如何实现鼠标随机移动效果

如果不想让鼠标继续动了那么点击close 就行了

到此,关于“Java如何实现鼠标随机移动效果”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI