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