![get mouse coordinates java get mouse coordinates java](https://i.stack.imgur.com/y2hUg.png)
![get mouse coordinates java get mouse coordinates java](https://i.stack.imgur.com/6DwR9.png)
You also need to set the content pane's layout to null if you want to set the location manually. You don't need a timer at all and you don't need to keep adding the component to the container. You can simply setLocation() on the panel and repaint() in your mouse listener.
#GET MOUSE COORDINATES JAVA HOW TO#
Your example does show how to get those coordinates, so I guess some might find it helpful in that regard, but it's overly complex for just moving a panel. The original question had nothing to do with moving panels. This method gets refreshed constantly by the timer while the JPanel is dragged. The method addComponent() has 6 parameters which will position the JPanel. NOTE: This won't match if panel is resized. 100 is not necessary, it is set to fit the panels current size. Means: xPos will be equal to X on screen(frame) - the x coordinate on the panel - 100 "yPos = evt.getYOnScreen() - getY() - 40 " The statements: "xPos = evt.getXOnScreen() - getX() - 100 " or We need to add MouseMotionListener in order to get the X and Y coordinates of the cursor on the screen. The timer will only start if Panel is dragged. YPos = evt.getYOnScreen() - getY() - void mouseMoved(MouseEvent evt) XPos = evt.getXOnScreen() - getX() - 100 Public void actionPerformed(ActionEvent e)ĪddComponent(contentPane, panel, xPos, yPos, 200, 200) Public void addComponent(Container container, SetTitle("Java Tutorial - Moving JPanels") Implements ActionListener, MouseListener, MouseMotionListenerĬontentPane = (JPanel) this.getContentPane() ĪddComponent(contentPane, panel, 40, 40, 100, 100) Public class MovingPnlDemo extends JFrame Here is an example: // Moving JPanel during runtime. Are you going to create moving JPanels during runtime, I recommend using MouseMotionListener and.