开发者

org.eclipse.swt.widgets.Button click from code

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!!!!");
   开发者_如何学Python }
}
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.


You can do this:

button.notifyListeners( SWT.MouseDown, null );

Where null is an Event. Remember that this is the Event received by your listener.


If you need all the listeners to be notified then you can try the below code,

yourbutton.notifyListeners(SWT.Selection, new Event());


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


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);


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜