Rubber Banding using XOR Mode


[Up]

Please click inside applet window.

Source Code

import java.awt.Graphics;
import java.awt.Event;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;

public class XRubber extends Applet 
             implements MouseListener, MouseMotionListener {
  int sx, sy, ex, ey, ox, oy;
  boolean first = false, erase = false;

  public void init() {
    setBackground(Color.white);
    addMouseListener(this);
    addMouseMotionListener(this);
  }
  public void update(Graphics g) {
    g.setColor(Color.white);
    g.setXORMode(Color.blue);
    if (erase == true) {
      g.drawLine(sx, sy, ox, oy);
    }
    g.drawLine(sx, sy, ex, ey);
    erase = true;
  }
  public void mouseEntered(MouseEvent evt) {}
  public void mouseExited(MouseEvent evt) {}
  public void mousePressed(MouseEvent evt) {}
  public void mouseReleased(MouseEvent evt) {}
  public void mouseClicked(MouseEvent evt) {
    int x, y;
    x = evt.getX(); y = evt.getY();
    if (first == true) {
      first = false;
      if ((ex != x) && (ey != y)) {
	ox = ex; oy = ey;
	ex = x; ey = y;
	repaint();
      }
      erase = false;
    }
    else {
      sx = x; sy = y;
      first = true;
      erase = false;
    }
  }
  public void mouseDragged(MouseEvent evt) {}
  public void mouseMoved(MouseEvent evt) {
    int x, y;
    x = evt.getX(); y = evt.getY();
    if (first == true) {
      ox = ex; oy = ey;
      ex = x; ey = y;
      repaint();
    }
  }
}

naniwa@rbt.his.fukui-u.ac.jp