Reputation: 4180
I am trying to click Button from code. I am tying to do the following:
class MyMouseAdapter extends MouseAdapter
{
public void mouseDown(MouseEvent evt)
{
System.out.println("Working!!!!");
}
}
Button button = new Button();
button.addMouseListener(new MyMouseAdapter());
now I want to run the mouseDown method from code could you tell me how to do it?
Thank you.
Upvotes: 13
Views: 11028
Reputation: 161
If you need all the listeners to be notified then you can try the below code,
yourbutton.notifyListeners(SWT.Selection, new Event());
Upvotes: 3
Reputation: 12718
To get the correct behavior from a mouse press on a button, you need to simulate the MouseDown
and MouseUp
using Display.post(...)
- there are no other way to get the correct architecture dependent behavior.
You can find plenty of code around for this - including Testing a Plug-in - User Interface Testing.
UPDATED the link
Upvotes: 1
Reputation: 4617
You can do this:
button.notifyListeners( SWT.MouseDown, null );
Where null
is an Event
. Remember that this is the Event
received by your listener.
Upvotes: 16
Reputation: 171
My answer is to essentially simulate the mouse click event. There is lots of examples out there so if my links don't work for you do a quick search. the answer depends on the libraries you are importing.
You could use the java.awt.Robot to simulate a programmic button press like at the following link.
http://www.java2s.com/Code/JavaAPI/java.awt/RobotmousePressintbuttons.htm
Or you if you are using SWT you could use Display.post(Event e) like at the following: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/UIAutomationfortestingtoolssnippetpostmouseevents.htm
Either of these routes require coordinates to be supplied for the click event and potentially a reference to the object being clicked, so it would require said objects finding the control (in this instance the button you are trying to click) so that it can be clicked.
If you are using swing just do button.doClick().
Upvotes: 0
Reputation: 5539
Not sure if it is the kind of solution you are looking for but why not keeping a local variable of your MyMouseAdapter instance and call the mouseDown method directly on it? Something like the following snippet:
class MyMouseAdapter extends MouseAdapter
{
public void mouseDown(MouseEvent evt)
{
System.out.println("Working!!!!");
}
}
MyMouseAdapter adapter = new MyMouseAdapter();
Button button = new Button();
button.addMouseListener(adapter);
//Somehow create a new MouseEvent then call the following:
adapter.mouseDown(yourNewEvent);
Upvotes: 0