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.
Joined: Jun 13, 2009
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.