APS Excellence in Physics Education Award
November 2019

Education Prize Logo
Science SPORE Prize
November 2011

NSF Logo
The Open Source Physics Project is supported by NSF DUE-0442581.

Mouse position. post and replies

Return to the Mouse position. thread
Login to post to this thread

Mouse position
Robert MacKay
5 Posts

How does one access the move position (x y) shown in the yellow box of the drawing panel?  I wanted to click on the screen and use the mouse position for a trace or a new drawable circle or rectangle.  This seems way too easy but I haven't yet found an example that uses this. Any help will be appreciated

Replies to Mouse position

Re: Mouse position -
Francisco Esquembre
232 Posts

Hi Robert,

Suppose your drawing panel is called "myDrawingPanel", then:

double x = _view.myDrawingPanel.getMouseX();
double y = _view.myDrawingPanel.getMouseY();

give you what you want in the panel world coordinates.


int px = _view.myDrawingPanel.getMouseIntX();
int py = _view.myDrawingPanel.getMouseIntY();

give you the point in pixels (if that is of any use for you).


Re: Re: Mouse position -
Robert MacKay
5 Posts

Thank you for your quick reply.  I'll give that a try.

Re: Re: Mouse position -
Robert MacKay
5 Posts

Hi Paco,
I tried your suggestion.

my drawing panel is named drawingPanel for this test.  My code in the evolution panel (of model) is:

int px = _view.drawingPanel.getMouseIntX();
int py = _view.drawingPanel.getMouseIntY();
_println("x= " +px +"y= "+py);

It seems to compile okay but I get the message (in output area)

Exception in thread "Thread-2" java.lang.NullPointerException
at org.opensourcephysics.display.InteractivePanel.getMouseIntX(Unknown Source)
at ch4.tryimage_pkg.tryimage._evolution1(tryimage.java:235)
at ch4.tryimage_pkg.tryimage._stepModel(tryimage.java:190)
at org.colos.ejs.library.Animation.step(Unknown Source)
at org.colos.ejs.library.Animation.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

I also tried
x = _view.drawingPanel.getMouseX();
y = _view.drawingPanel.getMouseY();

and got a similar error message.

Do I need to import something before running this or build a custom class?
Thank you for your patience.

Re: Re: Re: Mouse position -
Francisco Esquembre
232 Posts

Hi Bob,

I see that you are calling the methods in the Evolution. This will not work.

You must call the methods as response to a panel action (one of On Press, On Drag, or On Release). Only then, the methods return something sensible.

Otherwise, you get these null pointer errors.

In the attached example, the On Press action of the panel calls your code and prints the correct information.


Attached File: ejs_PanelClick.zip

Re: Re: Re: Re: Mouse position -
Robert MacKay
5 Posts

Thank you so much.  this should be perfect for my planned use.

OSP Projects:
Open Source Physics - EJS Modeling
Physlet Physics
Physlet Quantum Physics
STP Book