:-/ Is there any function in MouseListener that returns the x- and/or y-coordinates of the cursor relative to the origin of a JPanel which currently has the focus? ¡Ayúdenme, por favor!

Recommended Answers

All 15 Replies

The MouseEvent getX() and getY() methods will return the coordinates relative to the source of the event. If your panel is not that source, you will have to compute the coordinates yourself by adding them to the coordinates of the source (which also has getX() and getY() methods) within that panel. It just depends on the layering of your components and which is the source of the mouse event. This tutorial has more info if you need it:
http://java.sun.com/docs/books/tutorial/uiswing/events/mousemotionlistener.html

Thank you, Ezzaral. Helpful, concise, and 1337; just how the best answers are. Party on, dude.

Are you going to create moving JPanels during runtime, I recommend using MouseMotionListener and javax.swing.Timer.

Here is an example:

// Moving JPanel during runtime.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MovingPnlDemo extends JFrame 
               implements ActionListener, MouseListener, MouseMotionListener 
{
    private JPanel contentPane;
    private JPanel panel;
    
    private javax.swing.Timer timer;
    private int xPos, yPos;

    public MovingPnlDemo()
    {
        timer = new javax.swing.Timer(10,this);
        
        contentPane = new JPanel();
        contentPane = (JPanel) this.getContentPane();
        contentPane.setBackground(Color.BLUE);
        
        panel = new JPanel();
        panel.setOpaque(true);
        panel.setSize(100, 100);
        panel.setVisible(true);
        panel.setLayout(null);
        panel.addMouseMotionListener(this);

        addComponent(contentPane, panel, 40, 40, 100, 100);
        
        
        setTitle("Java Tutorial - Moving JPanels");
        setSize(800,600);
        setLocationRelativeTo(null);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void addComponent(Container container,
            Component c, int x, int y, int w, int h)
    {
        c.setBounds(x,y,w,h);
        container.add(c);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == timer)
        {
            addComponent(contentPane, panel, xPos, yPos, 200, 200);
        }
    }

    public void mouseDragged(MouseEvent evt)
    {
        timer.start();
        xPos = evt.getXOnScreen() - getX() - 100;
        yPos = evt.getYOnScreen() - getY() - 40;
    }

    @Override
    public void mouseMoved(MouseEvent evt){}
    public void mouseClicked(MouseEvent evt){}
    public void mouseEntered(MouseEvent evt){}
    public void mouseExited(MouseEvent evt){}
    public void mousePressed(MouseEvent evt){}
    public void mouseReleased(MouseEvent evt){}

    
    public static void main(String[] args)
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        try
        {
            UIManager.setLookAndFeel(
                    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            System.err.println("Could not set Look And Feel");
        }
      
        new MovingPnlDemo();
        
   }
}

The timer will only start if Panel is dragged.

We need to add MouseMotionListener in order to get the X and Y coordinates of the cursor on the screen.

The statements: "xPos = evt.getXOnScreen() - getX() - 100;" or
"yPos = evt.getYOnScreen() - getY() - 40;"
means: xPos will be equal to X on screen(frame) - the x coordinate on the panel - 100;
-100 is not necessary, it is set to fit the panels current size.
NOTE: This won't match if panel is resized.

The method addComponent() has 6 parameters which will position the JPanel.
This method gets refreshed constantly by the timer while the JPanel is dragged.

Hi @117
This problem is from 2007, when Ezzaral solved it comprehensively.
Do you really think the OP has waited four and a half years just in case you wanted to contribute?

Hi @117
This problem is from 2007, when Ezzaral solved it comprehensively.
Do you really think the OP has waited four and a half years just in case you wanted to contribute?

Hello @JamesCherrill
I didn't really pay attention to the date this was posted.
I keep the solution open for anyone else with a similar problem,
in case they want an example for a solution, because this is not the
first thread I've seen out there with this same question.

Because there wasn't really any example made based on azzeral's reply,
this can be considered the first.

I will now keep my eyes open for post dates.

The original question had nothing to do with moving panels. He just wanted mouse coordinates.

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. You can simply setLocation() on the panel and repaint() in your mouse listener. You don't need a timer at all and you don't need to keep adding the component to the container.

panel.setLocation(xPos, yPos);
repaint();

You also need to set the content pane's layout to null if you want to set the location manually.

The original question had nothing to do with moving panels. He just wanted mouse coordinates.

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. You can simply setLocation() on the panel and repaint() in your mouse listener. You don't need a timer at all and you don't need to keep adding the component to the container.

panel.setLocation(xPos, yPos);
repaint();

You also need to set the content pane's layout to null if you want to set the location manually.

Hello @ Azzeral

Thanks for the simpler version of moving JPanels.
However, I tried it and an error(No exception, but doesn't function the way it should) occur while dragging the JPanel (it is flickering): probably due to getX() and getY()
coordinates.

Do you know any way in order to get X and Y coordinates from the JPanel while moving the JPanel in the contentPane, to get the position inside the JPanel where the dragging occurs?, instead of getting the JPanel to the cursor when dragged.

(Panel jumps to the cursor when mouseDragged event occurs).

The version is clearly shorter and more useful tough I am stuck on this small little problem.

Any answer will be appreciated.

@117 please and a new quesion, your own question, before that please to read

1. Mouse Listener
2. Mouse-Motion Listener
3. Mouse-Wheel Listener

4. let's this too old thread

Hello @ mKorbel

The reason I didn't post a new thread was because the question weren't so big.
I've already solved half of the problem.
The only problem that persists is the getX and getY coordinates from the panel.
I already know how to use MouseListener, MouseMotionListener and MouseWheelListener.

This problem is different from what Oracle's Tutorials can provide.

Thanks for trying to solve this problem, If the problem is bigger than it seems to be.. I post a new thread about it.

You just need to keep track of the previous coordinates and update by the delta values

int prevX=0;
int prevY=0;

@Override
public void mousePressed(MouseEvent evt){
    prevX = evt.getXOnScreen();
    prevY = evt.getYOnScreen();
}

@Override
public void mouseDragged(MouseEvent evt)
{
    xPos = panel.getX() + evt.getXOnScreen() - prevX;
    yPos = panel.getY() + evt.getYOnScreen() - prevY;
    panel.setLocation(xPos, yPos);
    repaint();
    prevX = evt.getXOnScreen();
    prevY = evt.getYOnScreen();
}

You just need to keep track of the previous coordinates and update by the delta values

int prevX=0;
int prevY=0;

@Override
public void mousePressed(MouseEvent evt){
    prevX = evt.getXOnScreen();
    prevY = evt.getYOnScreen();
}

@Override
public void mouseDragged(MouseEvent evt)
{
    xPos = panel.getX() + evt.getXOnScreen() - prevX;
    yPos = panel.getY() + evt.getYOnScreen() - prevY;
    panel.setLocation(xPos, yPos);
    repaint();
    prevX = evt.getXOnScreen();
    prevY = evt.getYOnScreen();
}

Thanks for that brilliant solution,
I just experience this flicker, even when the JPanel is double-buffered,
as well as repainted.
Is there anyway to resolve this?

I have also added a container, from another class to the panel,
And when it updates, because this panel is resized,
the container from the other class is still the same size,
Do you know any solution to this?

If useful to know: I have a method called update()
which uses absolute positioning in order to arrange every container and component inside the main panel. This is called every time the panel is resized.

This is the only problem I need to resolve in order to go further into my development.
Therefor I didn't consider creating a new thread.

Start a new thread and post the relevant code or a small example that demonstrates the problem.

Start a new thread and post the relevant code or a small example that demonstrates the problem.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class sys_windows extends JPanel 
						 implements ActionListener, MouseMotionListener, MouseListener
{
	private JPanel titlebar, titlepane;
	public  JPanel content;
	private JLabel title;
	private int xPos, yPos, prevX, prevY = 0;
	private int xSize, ySize = 0;
	public JButton[] btn = new JButton[3];
	
	
	public Container container; public Component comp;
	
	public sys_windows()
	{
		titlebar = new JPanel();
		titlebar.setLayout(null);
		titlebar.setBackground(new Color(255,255,255, 10));
		titlebar.addMouseListener(this);
		titlebar.addMouseMotionListener(this);
		titlebar.setDoubleBuffered(true);
		titlebar.setOpaque(true);
		titlebar.setVisible(true);
		
		titlepane = new JPanel();
		titlepane.setLayout(null);
		titlepane.setBackground(new Color(255,255,255, 0));
		titlepane.setDoubleBuffered(true);
		titlepane.setOpaque(true);
		titlepane.setVisible(true);
		
		content = new JPanel();
		content.setLayout(new BorderLayout());
		content.setBackground(Color.WHITE);
		content.setBorder(BorderFactory.createEtchedBorder());
		content.addMouseListener(this);
		content.addMouseMotionListener(this);
		content.setDoubleBuffered(true);
		content.setOpaque(true);
		content.setVisible(true);
		
		for (int i=0; i<btn.length; i++)
		{
			btn[i] = new JButton();
			btn[i].setDoubleBuffered(true);
			btn[i].addActionListener(this);
			btn[i].setOpaque(false);
			btn[i].setBackground(new Color(0,80,130, 40));
			btn[i].setForeground(Color.WHITE);
			btn[i].setFont(new Font("SansSerif", Font.BOLD, 12));
			btn[i].setBorderPainted(true);
			btn[i].setContentAreaFilled(true);
			btn[i].setVisible(true);
		}
		
		title = new JLabel("", JLabel.LEFT);
		title.setForeground(Color.BLACK);
		title.setDoubleBuffered(true);
		
		btn[0].setText("x");
		btn[1].setText("+");
		btn[2].setText("--");
		
		setLayout(null);
		setBackground(new Color(255,255,255, 50));
		setBorder(BorderFactory.createEtchedBorder());
		addMouseListener(this);
		addMouseMotionListener(this);
		setSize(200,200);
		setOpaque(true);
		setVisible(true);
		
		update();
	}
	
	public void addComponent(Container container,
		Component c, int x, int y, int width, int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}
	
	public void setContent(Container container)
	{
		this.container.add(container);
		repaint();
		update();
	}
	
	public void update()
	{
		addComponent(this, content,  5,30, getWidth()-10, getHeight()-35);
		addComponent(titlepane, title, 5, 1, getWidth(), 30);
		addComponent(titlebar, titlepane, 0, 0, getWidth()-120, 30);
		addComponent(this, titlebar, 0,0, getWidth(), 30);
		addComponent(titlebar, btn[0], titlebar.getWidth()-btn[0].getWidth(), 2,45,20);
		addComponent(titlebar, btn[1], titlebar.getWidth()-btn[1].getWidth()-btn[0].getWidth(),2,38,20);
		addComponent(titlebar, btn[2], titlebar.getWidth()-btn[2].getWidth()-btn[1].getWidth()-btn[0].getWidth(), 2, 38, 20);
		repaint();
	}
	
	public void setTitle(String title)
	{
		this.title.setText(title);
	}
	
	
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == btn[0])
		{
			setVisible(false);
			setEnabled(false);
			Runtime.getRuntime().gc();
		}
		
		if (e.getSource() == btn[1])
		{
			
		}
		
		if (e.getSource() == btn[2])
		{
			setVisible(true);
		}
	}
	
	public void mouseDragged(MouseEvent e)
	{
		if (e.getSource() == this)
		{
			xSize = e.getX();
			ySize = e.getY();

			if (xSize < 120)
			{
				xSize = 120;
			}
			
			if (ySize < 40)
			{
				ySize = 40;
			}
			setSize(xSize, ySize);
			repaint();
			update();
		}
		
		if (e.getSource() == titlebar)
		{
			xPos = this.getX() + e.getXOnScreen() - prevX;
			yPos = this.getY() + e.getYOnScreen() - prevY;
			
			setLocation(xPos, yPos);
			repaint();
			
			prevX = e.getXOnScreen();
			prevY = e.getYOnScreen();
		}
	}
	
	public void mousePressed(MouseEvent e)
	{
		prevX = e.getXOnScreen();
		prevY = e.getYOnScreen();
		repaint();
	}
	
	public void mouseClicked(MouseEvent e)
	{

	}
	
	public void mouseReleased(MouseEvent e)
	{
	}
	
	public void mouseMoved(MouseEvent e)
	{
		
	}
	
	public void mouseEntered(MouseEvent e)
	{
		
	}
	
	public void mouseExited(MouseEvent e)
	{
		
	}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class sys_windows extends JPanel 
						 implements ActionListener, MouseMotionListener, MouseListener
{
	private JPanel titlebar, titlepane;
	public  JPanel content;
	private JLabel title;
	private int xPos, yPos, prevX, prevY = 0;
	private int xSize, ySize = 0;
	public JButton[] btn = new JButton[3];
	
	
	public Container container; public Component comp;
	
	public sys_windows()
	{
		titlebar = new JPanel();
		titlebar.setLayout(null);
		titlebar.setBackground(new Color(255,255,255, 10));
		titlebar.addMouseListener(this);
		titlebar.addMouseMotionListener(this);
		titlebar.setDoubleBuffered(true);
		titlebar.setOpaque(true);
		titlebar.setVisible(true);
		
		titlepane = new JPanel();
		titlepane.setLayout(null);
		titlepane.setBackground(new Color(255,255,255, 0));
		titlepane.setDoubleBuffered(true);
		titlepane.setOpaque(true);
		titlepane.setVisible(true);
		
		content = new JPanel();
		content.setLayout(new BorderLayout());
		content.setBackground(Color.WHITE);
		content.setBorder(BorderFactory.createEtchedBorder());
		content.addMouseListener(this);
		content.addMouseMotionListener(this);
		content.setDoubleBuffered(true);
		content.setOpaque(true);
		content.setVisible(true);
		
		for (int i=0; i<btn.length; i++)
		{
			btn[i] = new JButton();
			btn[i].setDoubleBuffered(true);
			btn[i].addActionListener(this);
			btn[i].setOpaque(false);
			btn[i].setBackground(new Color(0,80,130, 40));
			btn[i].setForeground(Color.WHITE);
			btn[i].setFont(new Font("SansSerif", Font.BOLD, 12));
			btn[i].setBorderPainted(true);
			btn[i].setContentAreaFilled(true);
			btn[i].setVisible(true);
		}
		
		title = new JLabel("", JLabel.LEFT);
		title.setForeground(Color.BLACK);
		title.setDoubleBuffered(true);
		
		btn[0].setText("x");
		btn[1].setText("+");
		btn[2].setText("--");
		
		setLayout(null);
		setBackground(new Color(255,255,255, 50));
		setBorder(BorderFactory.createEtchedBorder());
		addMouseListener(this);
		addMouseMotionListener(this);
		setSize(200,200);
		setOpaque(true);
		setVisible(true);
		
		update();
	}
	
	public void addComponent(Container container,
		Component c, int x, int y, int width, int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}
	
	public void setContent(Container container)
	{
		this.container.add(container);
		repaint();
		update();
	}
	
	public void update()
	{
		addComponent(this, content,  5,30, getWidth()-10, getHeight()-35);
		addComponent(titlepane, title, 5, 1, getWidth(), 30);
		addComponent(titlebar, titlepane, 0, 0, getWidth()-120, 30);
		addComponent(this, titlebar, 0,0, getWidth(), 30);
		addComponent(titlebar, btn[0], titlebar.getWidth()-btn[0].getWidth(), 2,45,20);
		addComponent(titlebar, btn[1], titlebar.getWidth()-btn[1].getWidth()-btn[0].getWidth(),2,38,20);
		addComponent(titlebar, btn[2], titlebar.getWidth()-btn[2].getWidth()-btn[1].getWidth()-btn[0].getWidth(), 2, 38, 20);
		repaint();
	}
	
	public void setTitle(String title)
	{
		this.title.setText(title);
	}
	
	
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == btn[0])
		{
			setVisible(false);
			setEnabled(false);
			Runtime.getRuntime().gc();
		}
		
		if (e.getSource() == btn[1])
		{
			
		}
		
		if (e.getSource() == btn[2])
		{
			setVisible(true);
		}
	}
	
	public void mouseDragged(MouseEvent e)
	{
		if (e.getSource() == this)
		{
			xSize = e.getX();
			ySize = e.getY();

			if (xSize < 120)
			{
				xSize = 120;
			}
			
			if (ySize < 40)
			{
				ySize = 40;
			}
			setSize(xSize, ySize);
			repaint();
			update();
		}
		
		if (e.getSource() == titlebar)
		{
			xPos = this.getX() + e.getXOnScreen() - prevX;
			yPos = this.getY() + e.getYOnScreen() - prevY;
			
			setLocation(xPos, yPos);
			repaint();
			
			prevX = e.getXOnScreen();
			prevY = e.getYOnScreen();
		}
	}
	
	public void mousePressed(MouseEvent e)
	{
		prevX = e.getXOnScreen();
		prevY = e.getYOnScreen();
		repaint();
	}
	
	public void mouseClicked(MouseEvent e)
	{

	}
	
	public void mouseReleased(MouseEvent e)
	{
	}
	
	public void mouseMoved(MouseEvent e)
	{
		
	}
	
	public void mouseEntered(MouseEvent e)
	{
		
	}
	
	public void mouseExited(MouseEvent e)
	{
		
	}
}

The most important words Ezzaral said were: "Start a new thread" Please :S. Go to the bottom of this page and there you should see This thread is solved and a few lines down.... start a new 'New Thread' and new thread is underlined! or if you must click here:http://www.daniweb.com/forums/newthread.php?do=newthread&f=9 it will do it for you

The most important words Ezzaral said were: "Start a new thread" Please :S. Go to the bottom of this page and there you should see This thread is solved and a few lines down.... start a new 'New Thread' and new thread is underlined! or if you must click here:http://www.daniweb.com/forums/newthread.php?do=newthread&f=9 it will do it for you

I have created a new thread, However nobody seems to know any solution to what appears to be a small problem.
If i'm wrong this may require a complete rewritten version of the class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.