NiceButton.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package view;
  2. import java.awt.Color;
  3. import java.awt.Image;
  4. import java.awt.Toolkit;
  5. import java.awt.event.MouseEvent;
  6. import java.awt.event.MouseListener;
  7. import java.awt.image.FilteredImageSource;
  8. import java.awt.image.ImageFilter;
  9. import java.awt.image.ImageProducer;
  10. import java.awt.image.RGBImageFilter;
  11. import javax.swing.ImageIcon;
  12. import javax.swing.JButton;
  13. /**
  14. * A {@link NiceButton} is a {@link JButton} that has an image on it.
  15. * @author kolja
  16. *
  17. */
  18. public class NiceButton extends JButton implements MouseListener {
  19. private static final long serialVersionUID = 1L;
  20. /**
  21. * creates a {@link NiceButton}
  22. * @param name the name of the image file, e.g. name="test" would correspond to "../img/test.png"
  23. */
  24. public NiceButton( String name )
  25. {
  26. 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() );
  27. setSize( 40, 40 );
  28. addMouseListener( this );
  29. setBorderPainted( false );
  30. }
  31. @Override
  32. public void mouseClicked(MouseEvent e) {}
  33. @Override
  34. public void mousePressed(MouseEvent e) {}
  35. @Override
  36. public void mouseReleased(MouseEvent e) {}
  37. @Override
  38. public void mouseEntered(MouseEvent e) {
  39. setBorderPainted( true );
  40. }
  41. @Override
  42. public void mouseExited(MouseEvent e) {
  43. setBorderPainted( false );
  44. }
  45. private static ImageIcon makeColorTransparent(final Image im, final Color color, int tolerance) {
  46. int temp = 0;
  47. if (tolerance < 0 || tolerance > 100) {
  48. temp = 0;
  49. } else {
  50. temp = tolerance * (0xFF000000 | 0xFF000000) / 100;
  51. }
  52. final int toleranceRGB = Math.abs(temp);
  53. final ImageFilter filter = new RGBImageFilter() {
  54. public int markerRGBFrom = (color.getRGB() | 0xFF000000) - toleranceRGB;
  55. public int markerRGBTo = (color.getRGB() | 0xFF000000) + toleranceRGB;
  56. public final int filterRGB(final int x, final int y, final int rgb) {
  57. if ((rgb | 0xFF000000) >= markerRGBFrom && (rgb | 0xFF000000) <= markerRGBTo) {
  58. return 0x00FFFFFF & rgb;
  59. } else {
  60. return rgb;
  61. }
  62. }
  63. };
  64. final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
  65. return new ImageIcon( Toolkit.getDefaultToolkit().createImage(ip) );
  66. }
  67. }