import java.awt.*; import javax.swing.*; import java.awt.event.*; public class TestMousePaintwithHandler extends JPanel implements MouseMotionListener, MouseListener { static private JFrame f; static private TextField tf; static private String title = "TestMousePaintwithHandler"; static private int x=100, y=100; public TestMousePaintwithHandler() { f = new JFrame(title); tf = new TextField(30); } public void paintComponent(Graphics g) { Graphics2D g2=(Graphics2D) g; g2.setColor(Color.red); g2.drawRect(x-1, y-1, 3, 3); System.out.println("The mouse : X = "+x + " Y = " + y); } public void mouseDragged(MouseEvent e) { tf.setText("The mouse dragged : X = "+e.getX() + " Y = " + e.getY()); } public void mouseEntered(MouseEvent e) { tf.setText("The mouse entered : X = "+e.getX() + " Y = " + e.getY()); } public void mouseExited(MouseEvent e) { tf.setText("The mouse exited : X = "+e.getX() + " Y = " + e.getY()); } public void mouseMoved(MouseEvent e) { // tf.setText("The mouse moved : X = "+e.getX() + " Y = " + e.getY()); x=e.getX(); y=e.getY(); repaint(); } public void mousePressed(MouseEvent e) { // tf.setText("The mouse pressed : X = "+e.getX() + " Y = " + e.getY()); } public void mouseReleased(MouseEvent e) { // tf.setText("The mouse released : X = "+e.getX() + " Y = " + e.getY()); } public void mouseClicked(MouseEvent e) { // tf.setText("The mouse clicked : X = "+e.getX() + " Y = " + e.getY()); } public static void main(String args[]) { MyWindowListener l = new MyWindowListener(); Label label = new Label("Click and drag the mouse"); TestMousePaintwithHandler p = new TestMousePaintwithHandler(); p.addMouseMotionListener(p); p.addMouseListener(p); f.getContentPane().add(label, BorderLayout.NORTH); f.getContentPane().add(p, BorderLayout.CENTER); f.getContentPane().add(tf, BorderLayout.SOUTH); f.addWindowListener(l); f.pack(); f.setSize(400, 200); f.setVisible(true); } } class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } }