KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > GrayFilter


1 /*
2  * @(#)GrayFilter.java 1.15 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package javax.swing;
8
9 import java.awt.*;
10 import java.awt.image.*;
11
12 /**
13  * An image filter that "disables" an image by turning
14  * it into a grayscale image, and brightening the pixels
15  * in the image. Used by buttons to create an image for
16  * a disabled button.
17  *
18  * @author Jeff Dinkins
19  * @author Tom Ball
20  * @author Jim Graham
21  * @version 1.15 12/19/03
22  */

23 public class GrayFilter extends RGBImageFilter {
24     private boolean brighter;
25     private int percent;
26     
27     /**
28      * Creates a disabled image
29      */

30     public static Image createDisabledImage (Image i) {
31     GrayFilter JavaDoc filter = new GrayFilter JavaDoc(true, 50);
32     ImageProducer prod = new FilteredImageSource(i.getSource(), filter);
33     Image grayImage = Toolkit.getDefaultToolkit().createImage(prod);
34     return grayImage;
35     }
36     
37     /**
38      * Constructs a GrayFilter object that filters a color image to a
39      * grayscale image. Used by buttons to create disabled ("grayed out")
40      * button images.
41      *
42      * @param b a boolean -- true if the pixels should be brightened
43      * @param p an int in the range 0..100 that determines the percentage
44      * of gray, where 100 is the darkest gray, and 0 is the lightest
45      */

46     public GrayFilter(boolean b, int p) {
47         brighter = b;
48         percent = p;
49
50     // canFilterIndexColorModel indicates whether or not it is acceptable
51
// to apply the color filtering of the filterRGB method to the color
52
// table entries of an IndexColorModel object in lieu of pixel by pixel
53
// filtering.
54
canFilterIndexColorModel = true;
55     }
56     
57     /**
58      * Overrides <code>RGBImageFilter.filterRGB</code>.
59      */

60     public int filterRGB(int x, int y, int rgb) {
61         // Use NTSC conversion formula.
62
int gray = (int)((0.30 * ((rgb >> 16) & 0xff) +
63                          0.59 * ((rgb >> 8) & 0xff) +
64                          0.11 * (rgb & 0xff)) / 3);
65     
66         if (brighter) {
67             gray = (255 - ((255 - gray) * (100 - percent) / 100));
68         } else {
69             gray = (gray * (100 - percent) / 100);
70         }
71     
72         if (gray < 0) gray = 0;
73         if (gray > 255) gray = 255;
74         return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0);
75     }
76 }
77
78
Popular Tags