import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class MouseMotionEventDemo extends JPanel implements MouseMotionListener { BlankArea blankArea = new BlankArea(new Color(0.98f, 0.97f, 0.85f)); JTextArea textArea = new JTextArea(); public MouseMotionEventDemo() { super(new BorderLayout()); add(blankArea,"North"); textArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setPreferredSize(new Dimension(200, 75)); add(scrollPane,"Center"); blankArea.addMouseMotionListener(this); addMouseMotionListener(this); setPreferredSize(new Dimension(450, 450)); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); } public void mouseMoved(MouseEvent e) { saySomething("Mouse moved", e); } public void mouseDragged(MouseEvent e) { saySomething("Mouse dragged", e); } void saySomething(String eventDescription, MouseEvent e) { textArea.append(eventDescription + " (" + e.getX() + "," + e.getY() + ")" + " detected on " + e.getComponent().getClass().getName() + "\n"); textArea.setCaretPosition(textArea.getDocument().getLength()); } public static void main(String[] args) { JFrame frame = new JFrame("MouseMotionEventDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent newContentPane = new MouseMotionEventDemo(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } } class BlankArea extends JLabel { Dimension minSize = new Dimension(100, 100); public BlankArea(Color color) { setBackground(color); setOpaque(true); setBorder(BorderFactory.createLineBorder(Color.black)); } public Dimension getMinimumSize() { return minSize; } public Dimension getPreferredSize() { return minSize; } }