GAMES LESSON TWELVE: Mouse Events

Mouse events are captured by a mouseListener just as keyboard events are captured by a keyListener. In this sample applet mouse events are captured and the coordinates at which the mouseEvent occured are used to place filled ovals of different colors around the applet area.

The portion of the code which deals with mouse events looks a lot like the portion of code which dealt with key events in the previous lesson:

this.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent m) { x[i] = m.getX(); y[i] = m.getY(); i++; i%=6; repaint(); } });

DOTS.java

import java.awt.*; import java.applet.*; import java.awt.event.*; public class DOTS extends Applet{ Dimension d; Image offI; int x[] = new int[6]; int y[] = new int[6]; int i; Color colors[] = { Color.red, Color.blue, Color.magenta, Color.green, Color.black, Color.cyan }; public void init(){ d = getSize(); offI=createImage(d.width,d.height); this.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent m) { x[i] = m.getX(); y[i] = m.getY(); i++; i%=6; repaint(); } }); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Graphics offG = offI.getGraphics(); offG.setColor(Color.yellow); offG.fillRect(0,0,d.width,d.height); for(int c = 0; c<colors.length; c++){ offG.setColor(colors[c]); if(x[c] != 0 && y[c] != 0) offG.fillOval(x[c],y[c],20,20); } offG.setColor(Color.black); offG.drawString("Click any where in applet area.", 10, d.height-5); g.drawImage(offI, 0,0, this); } }


ASSIGNMENT: