开发者

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();
                p开发者_开发技巧opup.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:

Getting the EXACT coords of Mouse in Java


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜