aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Getting a JLabel to follow the cursor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Getting a JLabel to follow the cursor" Watch "Getting a JLabel to follow the cursor" New topic
Author

Getting a JLabel to follow the cursor

Lance Gray
Greenhorn

Joined: Dec 06, 2011
Posts: 20
I am having a bit of a problem regarding the mouse. I am using MouseInfo.getPointerInfo().getLocation() to get the mouse pointer's location on the screen and trying to get a JLabel follow the mouse pointer.

When I do it on a new Project with a simple JFrame and the said JLabel, it works as it should. However, when I placed it on my real project, I encountered problems positioning the JLabel. The JLabel moves as the mouse moves but the location is wrong. The attached image explains how I set up my JFrame. The green area is the JFrame that contains all the components of my project. Inside it is the blue JPanel that holds other components. The re box is the JLabel I need to move. The purple are is another JPanel that holds yet other components. The orange ones are a custom JPanel.

I've set it up so that when the mouse enters the orange area, the red JLabel moves towards the cursor's position. Then when the cursor moves while inside the orange JPanel, the JLabel follows along. When the cursor leaves the orange JPanel, it resets back to its position. The problem is, the MouseListener is inside the orange JPanel and I'm controlling the red JLabel from there. When I tested it out, the position of the JLabel is wrong, or rather, is way off the desired position (as MouseInfo.getPointerInfo().getLocation() gets the position of the cursor on the screen).

How should I go about this problem? One solution I can think of is to remove the purple JPanel and simply put the orange ones on the blue JPanel. However, the orange JPanels are placed there on a loop with a set of conditions and parameters, meaning, the orange JPanels are dynamic and can be there or not. Any other possible solutions besides this one?

EDIT: I realized this was placed on a wrong forum. Sorry about that.



[Thumbnail for sample.png]

Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2182
    
    7
The MousePointer location is relative to the screen. You need the location of the label relative to its parent. Check out the SwingUtilities class. It has method that do point conversion for you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting a JLabel to follow the cursor