Is there any way to control mouse through java? - java

I want to control mouse by robot class. Just move to left or right. Meanwhile I run eclipse with administrator status. Here is my code below.
public class ControlMouse {
public static void main(String[] args) {
try {
Robot robot = new Robot();
Thread.sleep(1000);
robot.mouseMove(0, 0);
Thread.sleep(1000);
robot.delay(1000); // this one is the same...
robot.mouseMove(100, 100);
} catch (Exception e) {
System.out.println("e = " + e.toString());
} catch (Error e) {
System.out.println("e = " + e.toString());
}
}
}
But it seems doesn't work and no error or exception message. Dose any one may give me some advice? Thank you. The development environment is window 7. And I expect I can see the mouse cursor or traces will change. But I can’t.

You will have to put some delay and then check. without delay / sleep, sometimes GUI elements cannot be handled properly. You might even miss the event.
class ControlMouse {
public static void main(String[] args) {
try {
Robot robot = new Robot();
Thread.sleep(1000);
robot.mouseMove(0, 0);
Thread.sleep(1000);
robot.mouseMove(100, 100);
} catch (Exception e) {
System.out.println("e = " + e.toString());
} catch (Error e) {
System.out.println("e = " + e.toString());
}
}
}
The above code will work. It will move to 0,0 and then to 0,100

Related

If Radio box is selected, switch between two clicking methods

So i have this code here, and it quite literally doesn't work and i just don't know why. It doesn't click, doesn't print out anything. My goal is to make the buttons function as switches between two methods of clicking. Right mouse button clicks, and Left mouse button clicks. Can anyone tell me why this doesn't function?
if (rbRightClickRadioButton.isSelected()) {
System.out.println("RMB Clicker");
Robot clicker = null;
try {
clicker = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);
Thread.sleep(delay);
try {
clicker = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);
} else if (rbRightClickRadioButton.isSelected()) {
System.out.println("LMB Clicker");
Robot clicker = null;
try {
clicker = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);
Thread.sleep(delay);
try {
clicker = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);
If you want a button to work as a switch between two options, I would rather use checkbox than radiobutton. The main problem your code has right now is the simple fact that you check the same expression in your if statements.
You should either check if the other radiobutton is selected in your else if statement or just assume that if the rbRightClickRadioButton is not selected, then the other one is, and you don't use else if just a simple else.

Java AutoClicker with JNativeHook Runs infinitely

I have been trying to write this autoclicker with java for around 7 hours now. I wrote some of this based on other people's code, some by myself. I used JNativeHook to capture clicks in windows outside of Eclipse/the console.
The idea is this: When you hold left click, the Robot will left click for you with 300 ms in between each click.
The problem, however, is that when I left click, I do not execute the code to make the robot run. When I add the line "test.run();" in the nativeMousePressed listener, YES, it DOES autoclick, but when I release left click, It still runs. The only way to then stop it is to click the stop button on eclipse.
Now, I understand I need to make it run in a new thread so I can still use listeners with it, which I attempted to do with this in my MousePressed listener:
Thread test = new Thread(new Runnable() {
public void run() {
try {
Robot robot = new Robot();
System.out.println("GOT HERE 1");
System.out.println("Got HERE 4");
try {
Thread.sleep(300);
System.out.println("Got HERE 5");
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
// robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Got HERE 6");
// if ();
} catch (InterruptedException ex) {
}
} catch (AWTException e1) {
}
;
}
});
I already removed my loop because that did not seem to do anything to change it. Can somebody explain to me what is going wrong here?
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
public class AutoClicker implements NativeMouseInputListener {
public void nativeMouseClicked(NativeMouseEvent e) {
// dont need
}
public void nativeMousePressed(NativeMouseEvent e) {
if (e.getButton() == NativeMouseEvent.BUTTON1) {
System.out.println("Mouse Pressed: " + e.getButton());
run = true;
System.out.println(run);
Thread test = new Thread(new Runnable() {
public void run() {
try {
Robot robot = new Robot();
System.out.println("GOT HERE 1");
System.out.println("Got HERE 4");
try {
Thread.sleep(300);
System.out.println("Got HERE 5");
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
// robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Got HERE 6");
// if ();
} catch (InterruptedException ex) {
}
} catch (AWTException e1) {
}
;
}
});
}
}
public void nativeMouseReleased(NativeMouseEvent e) {
if (e.getButton() == NativeMouseEvent.BUTTON1) {
System.out.println("Mouse Released: " + e.getButton());
run = false;
System.out.println(run);
}
}
public void nativeMouseMoved(NativeMouseEvent e) {
// dont need
}
public void nativeMouseDragged(NativeMouseEvent e) {
// dont need
}
public void click() {
}
public static boolean run = false;
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
// Don't forget to disable the parent handlers.
logger.setUseParentHandlers(false);
// Construct the example object.
AutoClicker clicker = new AutoClicker();
// Add the appropriate listeners.
GlobalScreen.addNativeMouseListener(clicker);
}
}
Each mouse press triggers a click, So:
When you start your first click with a mouse press, it triggers the click after 300ms
which triggers another click and so on..
Basically the program gets stuck in an infinite loop of clicking, which i sometimes call the Clickening.
If i know what you're exactly trying to do, i might provide you with a better answer.
But as i understand your question now, a simple solution would just be, to only trigger the mouse release robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); and not do a mouse press. This will complete the click your started with your press after 300ms.
UPDATE: Per the OP's comment, here is the updated code, which uses alt to trigger clicking instead of the left mouse button.
Alt pressed --> clicking starts
Alt released --> clicking stops
Escape pressed --> program exits
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import java.awt.*;
import java.awt.event.InputEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AutoClicker implements NativeKeyListener {
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.exit(1);
}
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
// Don't forget to disable the parent handlers.
logger.setUseParentHandlers(false);
// Construct the example object.
AutoClicker clicker = new AutoClicker();
// Add the appropriate listeners.
GlobalScreen.addNativeKeyListener(clicker);
}
private void startClicking() {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Robot robot = new Robot();
while (isClicking) {
Thread.sleep(300);
System.out.println("Clicked!");
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
} catch (Exception ignored) {
System.out.println("Couldn't click");
}
}
};
Thread clickingThread = new Thread(runnable);
clickingThread.start();
}
private boolean isClicking = false;
#Override
public void nativeKeyPressed(NativeKeyEvent key) {
// When alt is pressed --> Start clicking
if (key.getKeyCode() == NativeKeyEvent.VC_ALT_L || key.getKeyCode() == NativeKeyEvent.VC_ALT_R) {
if (!isClicking) {
System.out.println("Alt pressed, started clicking!");
isClicking = true;
startClicking();
}
}
// If escape is clicked, exit the program
else if (key.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
System.out.println("Escape button Pressed.EXITING!");
System.exit(0);
}
}
#Override
public void nativeKeyReleased(NativeKeyEvent key) {
if (key.getKeyCode() == NativeKeyEvent.VC_ALT_L || key.getKeyCode() == NativeKeyEvent.VC_ALT_R) {
// When alt is relesed --> Stop clicking
isClicking = false;
System.out.println("Alt released, stopped clicking!");
}
}
#Override
public void nativeKeyTyped(NativeKeyEvent key) {
}
}
I don't know if I should be replying to this considering it is an old thread but I think I had might've found a way without using ALT or a trigger to enable the auto clicker. I had seen that if you were holding mouse button 1, and 100 ms later, the program programmatically releases mouse button1, then you release your real button 1, it says release twice (assuming you had added a print statement in the pressed method in JNativehook). This can be a signal to turn off the auto clicker when it says mouse button 1 that had been released. Hopefully that makes sense!

EDIT - Java while loop means events aren't called

So I've updated my code with the help of Cruncher, and now the clicker appears to work better. However whilst the while(pressed) loop is running, no other events are called & so it stays running.
public class Function implements NativeMouseListener {
private Robot robot;
private boolean pressed = false;
private boolean skip = false;
public Function()
{
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
private void repeatMouse()
{
skip = true;
robot.mouseRelease(InputEvent.BUTTON1_MASK);
while (pressed)
{
System.out.println("pressed while loop " + pressed);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void nativeMouseClicked(NativeMouseEvent nativeMouseEvent) {
}
#Override
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {
System.out.println("GG");
if (!(nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)) {
System.out.println("Returned.");
return;
}
if (!Native.get().getData().getEnabled())
{
System.out.println("Isn't enabled.");
return;
}
pressed = true;
repeatMouse();
}
#Override
public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {
System.out.println("released");
if (!(nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)) {
System.out.println("Returned 2");
return;
}
if (!skip)
{
System.out.println("pressed " + pressed);
pressed = false;
System.out.println("pressed " + pressed);
} else {
skip = false;
}
}
}
Any idea why the while loop would stop events from being called? Do I need to use multi threading or some of that jazz?
Thank you.
For one, your main method is not included in your code, but I assume it contains the following line(or similar):
new Project()
try {
bot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
while (pressed) {
bot.mousePress(InputEvent.BUTTON1_MASK);
//bot.mouseRelease(InputEvent.BUTTON1_MASK);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Now let's look at this code. When this runs, pressed will be false at the beginning(presumably), and it will just exit and not be running on later clicks.
What you want to do is have your loop started when you register a click. Let's move it into another method
private void repeatMouse() {
bot.mouseRelease(InputEvent.BUTTON1_MASK);
while (pressed) {
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Now let's call it in your mouse down native hook
#Override
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
pressed = true;
System.out.println(pressed);
repeatMouse();
}
}
EDIT:
It appears your other problem is that after the first mouseRelease, the handler will get called from the native library. I have a potential solution for this.
First next to where you define your pressed variable, define a new skipRelease
boolean skipRelease = false;
Then before every call to mouseRelease, first set skipRelease to true. Then change your mouseRelease handler to the following
#Override
public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
if(skipRelease) {
skipRelease = false;
return;
}
pressed = false;
System.out.println(pressed);
}
}

How to cause a left click then turn off thread?

private void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
while (running) {
try {
checkPixel();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void stop() {
this.running = false;
}
public void start() {
this.running = true;
}
So I have some code someone provided me to monitor the change in color in the middle of the screen. I want to essentially turn on/off checkPixel() after I press something like F9 but how can I do this without a GUI because I can't seem to find anything that allows this. I believe KeyListeners only work with GUIs?
EDIT: Ok so instead while I'm checking for pixel changes in the thread. Once a pixel change has been detected I want to cause create a "left click action" in checkPixel() then turn off the thread. Any help with this?
I guess you want functionality provided by JNativeHook library.
The library allows for grabbing a key from the backgrond.

Robot class - If a Button Is Pressed?

I have read and understood how the Robot class in java works. Only thing I would like to ask, is how do I press and release the mouse button inside an if statement. For example I would to make a click only if (and right after) the space button is pressed/released. I would use the code:
try {
Robot robot = new Robot();
if (/*insert my statement here*/) {
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {}
}
} catch (AWTException e) {}
Unfortunately, there isn't a way to directly control hardware (well, in fact there is, but you would have to use JNI/JNA), this means that you can't simply check if a key is pressed.
You can use KeyBindings to bind the space key to an action, when the spacebar is pressed you set a flag to true, when it's released you set that flag to false. In order to use this solution, your application has to be a GUI application, this won't work with console applications.
Action pressedAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
spaceBarPressed = true;
}
};
Action releasedAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
spaceBarPressed = false;
}
};
oneOfYourComponents.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressed");
oneOfYourComponents.getInputMap().put(KeyStroke.getKeyStroke("released SPACE"), "released");
oneOfYourComponents.getActionMap().put("pressed", pressedAction);
oneOfYourComponents.getActionMap().put("released", releasedAction);
Then, use
try {
Robot robot = new Robot();
if (spaceBarPressed) {
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {
//handle the exception here
}
}
} catch (AWTException e) {
//handle the exception here
}
As GGrec wrote, a better way to do it would be to execute your mouse press directly when the keyboard event is fired:
Action pressedAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {
//handle the exception here
}
}
};
My suggestion is that you listen for the keyboard event, and when you receive it, you execute your code without the if statement. Add the listener to your canvas, or whatever.
Careful not to recreate the Robot class each time.
new KeyAdapter() {
#Override
public void keyReleased(final KeyEvent e) {
if (e.keyCode == KeyEvent.VK_SPACE)
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {
}
}
}

Categories