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. import java.awt.*;
  9. import java.awt.image.*;
  10. /**
  11. * An image filter that "disables" an image by turning
  12. * it into a grayscale image, and brightening the pixels
  13. * in the image. Used by buttons to create an image for
  14. * a disabled button.
  15. *
  16. * @author Jeff Dinkins
  17. * @author Tom Ball
  18. * @author Jim Graham
  19. * @version 1.15 12/19/03
  20. */
  21. public class GrayFilter extends RGBImageFilter {
  22. private boolean brighter;
  23. private int percent;
  24. /**
  25. * Creates a disabled image
  26. */
  27. public static Image createDisabledImage (Image i) {
  28. GrayFilter filter = new GrayFilter(true, 50);
  29. ImageProducer prod = new FilteredImageSource(i.getSource(), filter);
  30. Image grayImage = Toolkit.getDefaultToolkit().createImage(prod);
  31. return grayImage;
  32. }
  33. /**
  34. * Constructs a GrayFilter object that filters a color image to a
  35. * grayscale image. Used by buttons to create disabled ("grayed out")
  36. * button images.
  37. *
  38. * @param b a boolean -- true if the pixels should be brightened
  39. * @param p an int in the range 0..100 that determines the percentage
  40. * of gray, where 100 is the darkest gray, and 0 is the lightest
  41. */
  42. public GrayFilter(boolean b, int p) {
  43. brighter = b;
  44. percent = p;
  45. // canFilterIndexColorModel indicates whether or not it is acceptable
  46. // to apply the color filtering of the filterRGB method to the color
  47. // table entries of an IndexColorModel object in lieu of pixel by pixel
  48. // filtering.
  49. canFilterIndexColorModel = true;
  50. }
  51. /**
  52. * Overrides <code>RGBImageFilter.filterRGB</code>.
  53. */
  54. public int filterRGB(int x, int y, int rgb) {
  55. // Use NTSC conversion formula.
  56. int gray = (int)((0.30 * ((rgb >> 16) & 0xff) +
  57. 0.59 * ((rgb >> 8) & 0xff) +
  58. 0.11 * (rgb & 0xff)) / 3);
  59. if (brighter) {
  60. gray = (255 - ((255 - gray) * (100 - percent) / 100));
  61. } else {
  62. gray = (gray * (100 - percent) / 100);
  63. }
  64. if (gray < 0) gray = 0;
  65. if (gray > 255) gray = 255;
  66. return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0);
  67. }
  68. }