20-CS-694 Advanced Programming Techniques Spring 2012
Mouse Actions

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

       Previous     Next        Applet Source     All lectures

Acting on Mouse Movement

Acting on mouse movement - display mouse coordinates. A JPanel is placed in the center of a JFrame's BorderLayout. The JPanel listens for mouse movements and reports current mouse positions to the JTextFields in a JPanel that is placed in the north section of the JFrame's BorderLayout.

Instructions: Move the mouse cursor. The changing position shows up in the two left JTextFields.

import java.awt.*;         // for Panel, TextField
import java.awt.event.*;   // for MouseMotionListener
import javax.swing.*;
import java.applet.*;

class MousePad extends JPanel implements MouseMotionListener {
   JTextField mouse_x, mouse_y;
   MousePad (JTextField x, JTextField y) {
      mouse_x = x;
      mouse_y = y;
      mouse_y.setBackground(new Color(162, 195, 255));
   public void mouseDragged (MouseEvent event) { }
   public void mouseMoved (MouseEvent event) {

class ShowMouseCoordsFrame extends JFrame {
   JTextField mouse_x, mouse_y;
   public ShowMouseCoordsFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,6));
      p.add(new JLabel("x: ",JLabel.RIGHT));
      p.add(mouse_x = new JTextField());
      p.add(new JLabel("y: ",JLabel.RIGHT));      
      p.add(mouse_y = new JTextField());
      p.add(new JLabel(""));
      p.add(new JTextField("Hello World"));
      add("North", p);
      MousePad mp = new MousePad(mouse_x, mouse_y);

public class ShowMouseCoords extends Applet {
   public void init () {
      ShowMouseCoordsFrame gf = new ShowMouseCoordsFrame();