// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
public class GrayButton extends Applet {
Image i, gray;
// Load an image from a file. Create a new image that is a grayer
// version of it, using a FilteredImageSoruce ImageProducer and a
// GrayFilter ImageFilter.
public void init() {
i = this.getImage(this.getDocumentBase(), "images/button.gif");
ImageFilter f = new GrayFilter();
ImageProducer producer = new FilteredImageSource(i.getSource(), f);
gray = this.createImage(producer);
}
// Display the image
public void paint(Graphics g) {
g.drawImage(i, 20, 20, this);
}
// When the user clicks, display the gray image
public boolean mouseDown(Event e, int x, int y) {
Graphics g = this.getGraphics();
Dimension d = this.size();
g.clearRect(0, 0, d.width, d.height);
g.drawImage(gray, 20, 20, this);
return true;
}
// And restore the normal one when the mouse goes up.
public boolean mouseUp(Event e, int x, int y) {
update(this.getGraphics());
return true;
}
}
// Filter an image by averaging all of its colors with white.
// This washes it out and makes it grayer.
class GrayFilter extends RGBImageFilter {
public GrayFilter() { canFilterIndexColorModel = true; }
public int filterRGB(int x, int y, int rgb) {
int a = rgb & 0xff000000;
int r = ((rgb & 0xff0000) + 0xff0000)/2;
int g = ((rgb & 0x00ff00) + 0x00ff00)/2;
int b = ((rgb & 0x0000ff) + 0x0000ff)/2;
return a | r | g | b;
}
}
|