Simulate a MouseEvent - java

I'd like to simulate a Mouse click on a Graphic. I added a Mouselistener, and some action when the mouseclick is done, but I really need to simulate that the user clicked on my Graphic in my programm... How can I say something like "" MouseEvent e is performed!"" ?
Actually I'd like to clean a "Graphics 2D canvas" when you click on a Jbutton called "Clean". But the thing is that the cleaning action would be done only if the user click on my "Graphics 2D canvas". I'd like to make the illusion that the "Graphics 2D canvas" was cleaned by clicking on the JButton..
Thanks.
addMouseListener(this);
addMouseMotionListener(this);
public void mousePressed(MouseEvent e) {
e.consume();
x1=e.getX();
y1=e.getY();
if(figure==1 || figure==3 ) {x2=x1; y2=y1;}
; }
PS : I can't use robot because I have to run my programm on every OS, and someone told me I can't run this on every programm :
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// SET THE MOUSE X Y POSITION
robot.mouseMove(65*Fond_noir.pourcent_largeur, 16*Fond_noir.pourcent_hauteur);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}

Well, you're right about Robot. It's platform dependent, and there are no guarantees that it will support all features on all platforms, from the JavaDoc:
Note that some platforms require special privileges or extensions to
access low-level input control. If the current platform configuration
does not allow input control, an AWTException will be thrown when
trying to construct Robot objects. For example, X-Window systems will
throw the exception if the XTEST 2.2 standard extension is not
supported (or not enabled) by the X server.
To simulate the click, you can simply do this:
JButton buttonToSimulateClicking = new JButton(...);
buttonToSimulateClicking.doClick(); // As simple as that !
If you have to simulate the click "the hard way", i.e. to simulate a mouse click, you can always do the following:
MouseEvent clickEvent = new MouseEvent(buttonToSimulateClicking, MouseEvent.MOUSE_CLICKED, ...);
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.dispatchEvent(clickEvent);

Related

how to popup javafx application?

I have a javafx application which represents for the user the rates of currencies.
I want to be able to pop up the application when some trigger happen, even if the user has the application minimized.
For example: suppose the $ currency is hitting a target of 1$ = 0.86€, I want to alert the user, even if he has the application minimized on his screen, and bring it to the front.
Is that possible?
I think you should use setIconified, setX and setY methods from Stage and put it into a thread. Check this:
while(alive){
if(##YOUR STATEMENT##){
Rectangle2D screenBounds = Screen.getPrimary().getBounds();
primaryStage.setX((screenBounds.getMaxX() - primaryStage.getWidth()) / 2);
primaryStage.setY((screenBounds.getMaxY() - primaryStage.getHeight()) / 2);
primaryStage.setIconified(false);
primaryStage.setAlwaysOnTop(true);
}
try {
Thread.sleep(CHECK_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This will show your window exactly at the center of the screen.

Java Robot click side button

I want to use Robot to click mouse button 4, side button.
The InputEvent only have the 3 standard left, middle (scroll) and right buttons.
InputEvent.BUTTON1_DOWN_MASK = 1024
InputEvent.BUTTON2_DOWN_MASK = 2048
InputEvent.BUTTON3_DOWN_MASK = 4096
So I tried to flow the formula and send to the Robot the number 8192
public static void main(String[] args)
{
try
{
Robot mouseHandler = new Robot();
mouseHandler.mousePress(8192);
mouseHandler.mouseRelease(8192);
} catch (AWTException e)
{
e.printStackTrace();
}
}
but it didn't work (as expected) and throws an exception:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid combination of button flags
at java.awt.Robot.checkButtonsArgument(Robot.java:320)
at java.awt.Robot.mousePress(Robot.java:256)
at controller_client.MainClass.main(MainClass.java:30)
Is it possible to create a mouse click with button 4?
Ok so after searching more I found this function that return any mouse button mask from 1 to 20 MouseEvent.getMaskForButton(int button).
After trying it the Robot class did manage to click the button4 and button5, side buttons, like so:
try
{
Robot mouseHandler = new Robot();
int mouseButtonNum = 4; // 1 - 20
// but only buttons from 1 to 5 did work with Robot
mouseHandler.mousePress(MouseEvent.getMaskForButton(mouseButtonNum));
mouseHandler.mouseRelease(MouseEvent.getMaskForButton(mouseButtonNum));
} catch (AWTException e)
{
e.printStackTrace();
}
I used a mouse with 3 buttons and Robot did manage to click 4 and 5 buttons. But it seems like that Robot only can click buttons from 1 to 5, so
probably Hovercraft Full Of Eels's explanation is correct:
I also have to wonder if your issue is not only OS-specific, but also vendor-specific, since I don't know if handling of extra and perhaps unusual mouse buttons has been fully addressed by most common OS's.
If he does right then the OS that I use is Windows 10. If someone have Linux and he knows how to address more mouse buttons to Linux and tried to make Robot click mouse button above 5 so please note me if it works or not.

java - Detect Mouse Clicks Anywhere On Screen

I want my app to detect mouse clicks anywhere on the screen without having to have the app focused. I want it to detect mouse events universally even if its minimized. So far I've only been able to detect mouse events within a swing gui.
Autohotkey can detect mouse clicks and get the mouse's position at any time, how can I do this with java?
It is possible with a little trick. Should be 100% cross-platform (tested on Linux & Windows). Basically, you create a small JWindow, make it "alwaysOnTop" and move it around with the mouse using a timer.
Then, you can record the click, dismiss the window and forward the click to the actual receiver using the Robot class.
Short left and right clicks work completely fine in my tests.
You could also simulate dragging and click-and-hold, just forwarding that seems harder.
I have code for this, but it is in my Java extension (JavaX). JavaX does translate into Java source code, so you can check out the example here.
The code in JavaX:
static int windowSize = 11; // odd should look nice. Set to 1 for an invisible window
static int clickDelay = 0; // Delay in ms between closing window and forwarding click. 0 seems to work fine.
static int trackingSpeed = 10; // How often to move the window (ms)
p {
final new JWindow window;
window.setSize(windowSize, windowSize);
window.setVisible(true);
window.setAlwaysOnTop(true);
JPanel panel = singleColorPanel(Color.red);
window.setContentPane(panel);
revalidate(window);
final new Robot robot;
panel.addMouseListener(new MouseAdapter {
// public void mousePressed(final MouseEvent e) {}
public void mouseReleased(final MouseEvent e) {
print("release! " + e);
window.setVisible(false);
int b = e.getButton();
final int mod =
b == 1 ? InputEvent.BUTTON1_DOWN_MASK
: b == 2 ? InputEvent.BUTTON2_DOWN_MASK
: InputEvent.BUTTON3_DOWN_MASK;
swingLater(clickDelay, r {
print("clicking " + mod);
robot.mousePress(mod);
robot.mouseRelease(mod);
});
}
});
swingEvery(window, trackingSpeed, r {
Point p = getMouseLocation();
window.setLocation(p.x-windowSize/2, p.y-windowSize/2);
//print("moving");
});
}

Java Mouse After a Drag

I'm making a small game project in Java. In it you have a character that shoots in the direction of the mouse when "pressed" or "dragged" (you know, in Java's terms). The only problem is that if you stop dragging but you still hold the left mouse button down you stop shooting.
Is there a way to detect if the mouse button is down after a drag?
NOTE: the mouse is not sensed as "pressed" after the drag.
You will get the information when a mouse button is pressed and when it is released again. If you want to know the state in between, you need to use a boolean to store that information.
Example:
final boolean[] buttonStates = new boolean[3];
public void mousePressed(MouseEvent e) {
buttonStates[e.getButton()] = true;
}
public void mouseReleased(MouseEvent e) {
buttonStates[e.getButton()] = false;
}
You would do the same for keyboard input by the way.

How do I set the position of the mouse in Java?

I'm doing some Swing GUI work with Java, and I think my question is fairly straightforward; How does one set the position of the mouse?
As others have said, this can be achieved using Robot.mouseMove(x,y). However this solution has a downfall when working in a multi-monitor situation, as the robot works with the coordinate system of the primary screen, unless you specify otherwise.
Here is a solution that allows you to pass any point based global screen coordinates:
public void moveMouse(Point p) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
// Search the devices for the one that draws the specified point.
for (GraphicsDevice device: gs) {
GraphicsConfiguration[] configurations =
device.getConfigurations();
for (GraphicsConfiguration config: configurations) {
Rectangle bounds = config.getBounds();
if(bounds.contains(p)) {
// Set point to screen coordinates.
Point b = bounds.getLocation();
Point s = new Point(p.x - b.x, p.y - b.y);
try {
Robot r = new Robot(device);
r.mouseMove(s.x, s.y);
} catch (AWTException e) {
e.printStackTrace();
}
return;
}
}
}
// Couldn't move to the point, it may be off screen.
return;
}
You need to use Robot
This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.
Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events...
Robot.mouseMove(x,y)
Check out the Robot class.
The code itself is the following:
char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
This code is incomplete by itself, so I recommend placing it in a method and calling it something like 'positionCursor(int row, int column)'.
Here is the code in full (method and code):
void positionCursor(int row, int column) {
char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
}

Categories

Resources