Search code examples
javaawtmousemotionlistener

how to Combine MouseMotionListener and JPanel in java


I searched all over the Internet but could not find out why the circle is appears to be distorted beyond the middle of the JFrame(sorry,no image because i needed 10 reputation to post images). I checked my code but found no errors.I'm a newbie to java GUI programming . This is my code so far:

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

public class test1 extends JPanel implements MouseMotionListener
{

private static final long serialVersionUID = -2068330714634802982L;
public int Mousex,Mousey;
public void init()
{
    addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e)
{
     Mousex=e.getX();
     Mousey=e.getY();
    repaint();
}
public void mouseDragged(MouseEvent e){}


 public void paintComponent(Graphics g)
{
    Graphics2D g2=(Graphics2D)g;
    g2.setColor(Color.GREEN);
    g2.fillOval(Mousex,Mousey,50,50);

}


public static void main(String[] args)
{   
    test1 t=new test1();
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1305,650);
    frame.setLocationRelativeTo(null);
    frame.getContentPane().add(t);
    frame.setResizable(true);
    frame.setVisible(true);
}
}

Solution

  • You need to call

    t.init();
    

    to register the MouseMotionListener. Also super.paintComponent(g); in the needs to be invoked in the paintComponent method to repaint the parent container otherwise the last rectangle wont be clearly visible.