NiceButton.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package view;
  2. import java.awt.Color;
  3. import java.awt.Image;
  4. import java.awt.Toolkit;
  5. import java.awt.image.FilteredImageSource;
  6. import java.awt.image.ImageFilter;
  7. import java.awt.image.ImageProducer;
  8. import java.awt.image.RGBImageFilter;
  9. import javax.swing.ImageIcon;
  10. import javax.swing.JButton;
  11. /**
  12. * A {@link NiceButton} is a {@link JButton} that has an image on it AND looks nice.
  13. * @author kolja
  14. *
  15. */
  16. public class NiceButton extends JButton {
  17. private static final long serialVersionUID = 1L;
  18. /**
  19. * creates a {@link NiceButton}
  20. * @param name the name of the image file, e.g. name="test" would correspond to "/img/test.png"
  21. */
  22. public NiceButton( String name )
  23. {
  24. super( NiceButton.class.getResource( "/img/" + name + ".png" ) != null ? makeColorTransparent( new ImageIcon( NiceButton.class.getResource( "/img/" + name + ".png" ) ).getImage().getScaledInstance( 40, 40, Image.SCALE_AREA_AVERAGING ), Color.WHITE, 0 ) : new ImageIcon() );
  25. setSize( 40, 40 );
  26. }
  27. private static ImageIcon makeColorTransparent(final Image im, final Color color, int tolerance) {
  28. int temp = 0;
  29. if (tolerance < 0 || tolerance > 100) {
  30. temp = 0;
  31. } else {
  32. temp = tolerance * (0xFF000000 | 0xFF000000) / 100;
  33. }
  34. final int toleranceRGB = Math.abs(temp);
  35. final ImageFilter filter = new RGBImageFilter() {
  36. public int markerRGBFrom = (color.getRGB() | 0xFF000000) - toleranceRGB;
  37. public int markerRGBTo = (color.getRGB() | 0xFF000000) + toleranceRGB;
  38. public final int filterRGB(final int x, final int y, final int rgb) {
  39. if ((rgb | 0xFF000000) >= markerRGBFrom && (rgb | 0xFF000000) <= markerRGBTo) {
  40. return 0x00FFFFFF & rgb;
  41. } else {
  42. return rgb;
  43. }
  44. }
  45. };
  46. final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
  47. return new ImageIcon( Toolkit.getDefaultToolkit().createImage(ip) );
  48. }
  49. }