test
test

Reputation: 18198

Getting the EXACT coords of Mouse in Java

Alright, I know HOW to do but It's doing something weird.

I am trying to get the correct X Y coords for a JMenu to appear. I've found a way but it's only a hack. All the right-clicking takes place on the JList, for now until I add character panel, so let's say you right-click near the top-left. You expect the Y coord to be around 40~ pixels and the Y coord to be around 100~ pixels right? Because you're clicking on the near left where the JList is. Wrong. The x y coords count from the top left of the JList when I want it to count from the top left of the WHOLE application. :S

So, what did I do? Since the Y coord is correct, I added 512 pixels to the X coord so it's always in the JList. Like so:

                int newMouseX = 512+e.getX();
                popup.show(tileOffline.this, newMouseX, e.getY()); // show item at mouse

However, as you can tell I will not be right-clicking in the JList forever.

How can I make it so I get the exact X Y coords of the mouse from the WHOLE applet?

Here's a pic to describe the situation WITHOUT the 512 hack: enter image description here

Upvotes: 1

Views: 399

Answers (4)

Erick Robertson
Erick Robertson

Reputation: 33082

Use the MouseEvent.getXOnScreen() and MouseEvent.getYOnScreen() methods.

The MouseEvent that gets generated when you move or click a mouse contains the absolute coordinates on the screen. Use these two methods to get them.

Upvotes: 0

Andy Mikula
Andy Mikula

Reputation: 16780

You can use convertPointToScreen in javax.swing.SwingUtilities to convert to screen coordinates - just pass in the component that you're clicking!

convertPointToScreen(Point p, Component c)

http://download.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html

Upvotes: 1

gcooney
gcooney

Reputation: 1699

I wonder if you're making this harder than it needs to be. The popup menu will position itself relative to the component you pass into the show method (JPopupMenu API). You should just be able to show the popupmenu doing something like this in order to get it to show at the correct location:

popup.show(myJList, e.getX(), e.getY());

Upvotes: 4

trashgod
trashgod

Reputation: 205875

SwingUtilities has methods suitable for converting to and from screen coordinates, as well as among Components.

Upvotes: 2

Related Questions