本篇内容主要讲解“Java如何实现按键精灵”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java如何实现按键精灵”吧!
实现效果
背景
对于日常刷课每十分钟点击“继续学习”的行为,或者说是单机游戏里某项重复的行为想使其实现“自动化”。我们可以通过JavaFx里的Robot类来实现。
难点
窗口穿透
鼠标行为的记录
搭建程序
需要掌握的知识
窗口测试
@Overridepublic void start(Stage stage) throws Exception { Scene scene = new Scene(new Pane (), 320, 240); stage.setTitle("按键精灵!"); stage.setScene(scene); stage.show();}
获取鼠标位置
Robot robot = new Robot ();//获得鼠标位置Point2D mp = robot.getMousePosition ();System.out.println (mp);
模拟鼠标单击
左
MouseButton.PRIMARY
右
MouseButton.SECONDARY
滚轮子
MouseButton.MIDDLE
模拟鼠标移动
//鼠标移动robot.mouseMove (new Point2D (800,800));
鼠标行为监听
//监听鼠标单击pane.setOnMouseClicked (e->{ System.out.println (e.getButton ()); System.out.println (e.getSceneX ()); System.out.println (e.getSceneY ());});//监听鼠标键入pane.setOnMousePressed (e->{});//监听鼠标释放pane.setOnMouseReleased (e->{});//监听鼠标在摁着某个键时的拖动pane.setOnMouseDragged (e->{});
完整源码及详细解释
public class QMApp extends Application { @Override public void start(Stage stage) throws Exception { class MyMouseEvent{ //鼠标行为 MouseButton mb; //类型 EventType et; //坐标 Point2D point2D; public MyMouseEvent(MouseButton mb, EventType et, Point2D point2D) { this.mb = mb; this.et=et; this.point2D = point2D; } } //创建面板 VBox pane = new VBox (); //对齐方式 pane.setAlignment (Pos.TOP_LEFT); //robot关键对象 Robot robot = new Robot (); //记录鼠标行为 LinkedList<MyMouseEvent> list = new LinkedList<> (); //开始 Button beginb = new Button ("开始"); beginb.setTextFill (Color.RED); //结束 Button endb = new Button ("结束"); endb.setTextFill (Color.RED); pane.getChildren ().addAll (beginb,endb); //点击“开始”按钮时,鼠标行为储存进列表 beginb.setOnMouseClicked (m->{ pane.setOnMouseDragged (e->{ list.add (new MyMouseEvent (e.getButton (),e.getEventType (),new Point2D (e.getSceneX (),e.getSceneY ()))); }); pane.setOnMousePressed (e->{ list.add (new MyMouseEvent (e.getButton (),e.getEventType (),new Point2D (e.getSceneX (),e.getSceneY ()))); }); pane.setOnMouseReleased (e->{ list.add (new MyMouseEvent (e.getButton (),e.getEventType (),new Point2D (e.getSceneX (),e.getSceneY ()))); }); }); //点击“结束”按钮时,鼠标行为储存进列表 endb.setOnMouseClicked (e->{ pane.getChildren ().remove (beginb); for (int i = 0; i < list.size (); i++) { //每次鼠标模拟都将窗口透明,实现穿透 stage.setOpacity (0); if (list.get (i).et== MOUSE_DRAGGED){ robot.mousePress (list.get (i).mb); }else { robot.mouseMove (list.get (i).point2D); robot.mouseClick (list.get (i).mb); } try { //为了效果明显,进行延迟 Thread.sleep (50); } catch (InterruptedException ex) { ex.printStackTrace (); } } }); //面板不参与计算边界。鼠标点击事件发生后,会计算应该是哪个组件位于鼠标所在点的位置,而该面板因为不参与边界计算,所以也不会捕获到鼠标事件 pane.setPickOnBounds(false); //窗口在前,不能拖到,都没有 stage.initStyle (StageStyle.UNDECORATED); //窗口最大化 stage.setMaximized (true); //窗口透明度,为了使得开始按钮不会消失同时可以看见其他窗口,半透明 stage.setOpacity (0.3); Scene scene = new Scene(pane); stage.setTitle("按键精灵"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch (args); }}
到此,相信大家对“Java如何实现按键精灵”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!