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

Mouse Click

Acting on a mouse click - adding a button. A JButton is added and an ActionListener is implemented (method actionPerformed) to handle button pressed. This example puts the code of the MousePad class inside main class (namely MouseClickFrame).

Instructions: Click the reset button to set the mouse click count to 0.

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

class MouseClickFrame extends JFrame
   implements ActionListener, MouseMotionListener {
   JTextField mouse_x, mouse_y, count;
   JButton reset_button;
   
   MouseAdapter ma = new MouseAdapter() {
      public void mousePressed (MouseEvent event) {
         try {
            count.setText(String.valueOf(Integer.parseInt(count.getText())+1));
         }
         catch (Exception e) {
            count.setText("0");
         }
      }
   };
   
   public MouseClickFrame () {
      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("count:",JLabel.RIGHT));
      p.add(count = new JTextField("0"));
      add("North", p);
      
      p = new JPanel();
      p.setLayout(new GridLayout(1,3));
      p.add(new JLabel(""));
      p.add(reset_button = new JButton("Reset"));
      p.add(new JLabel(""));
      add("South",p);
      
      addMouseMotionListener(this);
      addMouseListener(ma);
      reset_button.addActionListener(this);
      
      mouse_x.setEditable(false);
      mouse_x.setBackground(Color.yellow);
      mouse_y.setEditable(false);
      mouse_y.setBackground(Color.blue);
   }
   
   public void actionPerformed (ActionEvent event) {
      if (event.getSource() == reset_button) {
         count.setText("0");
      }
   }
   
   public void mouseMoved (MouseEvent event) {
      mouse_x.setText(String.valueOf(event.getX()));
      mouse_y.setText(String.valueOf(event.getY()));
   }

   public void mouseDragged (MouseEvent event) { }
}

public class MouseClick extends Applet {
   public void init () {
      MouseClickFrame ff = new MouseClickFrame();
      ff.setSize(500,300);
      ff.setVisible(true);
   }
}