import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
public class FadingButton extends JButton
{
private BufferedImage image = null;
private float fadeValue = 0;
public FadingButton(Action a)
{
super(a);
}
public FadingButton(Icon icon)
{
super(icon);
}
public FadingButton(String text)
{
super(text);
}
public FadingButton(String text, Icon icon)
{
super(text, icon);
}
@Override
public void paintComponent(Graphics gr)
{
Graphics2D g = (Graphics2D) gr;
if (image == null || image.getWidth() != getWidth() ||
image.getHeight() != getHeight())
{
image = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_RGB);
}
Graphics2D ig = (Graphics2D) image.getGraphics();
ig.setFont(g.getFont());
ig.setStroke(g.getStroke());
super.paintComponent(ig);
//System.out.println("fadeValue "+fadeValue);
for (int x = 0; x < image.getWidth(); x++)
{
for (int y = 0; y < image.getHeight(); y++)
{
image.setRGB(x, y, filter(image.getRGB(x, y)));
}
}
g.drawImage(image, 0, 0, this);
}
private float hsb[] = new float[3];
private int filter(int rgb)
{
float brightness = getBrightnessFor(rgb);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 0) & 0xFF;
Color.RGBtoHSB(r, g, b, hsb);
hsb[1] *= (1 - fadeValue);
hsb[2] = (1-fadeValue) * hsb[2] + fadeValue * brightness;
int result = 0xFF000000 | Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]);
return result;
}
private float getBrightnessFor(int rgbIn)
{
int rgb = getAsGray(rgbIn);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 0) & 0xFF;
Color.RGBtoHSB(r, g, b, hsb);
return hsb[2];
}
private int getAsGray(int rgb)
{
int percent = 72;
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 0) & 0xFF;
int gray = (int)((0.30 * r + 0.59 * g + 0.11 * b) / 3);
gray = (255 - ((255 - gray) * (100 - percent) / 100));
if (gray < 0) gray = 0;
if (gray > 255) gray = 255;
return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0);
}
public void setFaded(final boolean faded)
{
Thread thread = new Thread(new Runnable()
{
public void run()
{
for (int i = 0; i < 100; i++)
{
fadeValue = (float) i / 100;
if (!faded)
{
fadeValue = 1.0f - fadeValue;
}
repaint();
try
{
Thread.sleep(10);
}
catch (Exception e)
{}
}
}
});
thread.start();
}
}