I was experimenting with code found on this SO post regarding custom buttons made with BasicButtonUI. I am trying to make my custom button fade when pressed, but for some reason I am unable to see any results. I made a SSCCE to illustrate the problem:
I put a print statement inside the timer to verify that it was working, making me believe there was something wrong with the way I am repainting.
import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.event.*;
class StyledButtonUI extends BasicButtonUI {
@Override
public void installUI (JComponent c) {
super.installUI(c);
AbstractButton button = (AbstractButton) c;
button.setOpaque(false);
button.setBorder(BorderFactory.createEmptyBorder (5, 15, 5, 15));
}
@Override
public void paint (Graphics g, JComponent c) {
AbstractButton b = (AbstractButton) c;
paintBackground(g, b, b.getModel().isPressed () ? true : false);
super.paint(g, c);
}
private void paintBackground (final Graphics g, final JComponent c, boolean fade) {
final Dimension size = c.getSize();
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//draws normal button
g.setColor (c.getBackground ());
g.fillRoundRect (0, 0, size.width, size.height - 5, 10, 10);
if (fade) {
Timer timer = new Timer (50, new ActionListener () {
int i = 0;//starting opacity
int limit = 15;//opacity limit
public void actionPerformed (ActionEvent ae) {
if (i <= limit) {
System.out.println ("background color: " + c.getBackground () + " alpha: " + c.getBackground ().getAlpha () + " new fade in color: " + getAlphaColor (c.getBackground (), i) + " fade in alpha: " + i);
g.setColor (getAlphaColor (c.getBackground (), i));
g.fillRoundRect(0, 0, size.width, size.height - 5, 10, 10);
i++;
}
else {
((Timer) ae.getSource ()).stop ();
}
}});
timer.start ();
}
}
private Color getAlphaColor (Color color, int newAlpha) {
return new Color (color.getRed (), color.getGreen (), color.getBlue (), newAlpha);
}
public static void main (String[] args) {
JFrame f = new JFrame("Button UI Test");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel p = new JPanel();
p.setBackground(Color.WHITE);
f.setContentPane(p);
for (int i = 1; i <= 5; i++) {
final JButton button = new JButton("Button #" + i);
button.setBackground(Color.BLACK);
button.setForeground(Color.WHITE);
button.setUI(new StyledButtonUI());
p.add(button);
}
f.pack();
f.setLocation(500, 500);
f.setVisible(true);
}
}