repaint swing button with different gradient
The easiest approach is to use setPressedIcon()
, but you can also override paint()
in the ButtonUI
delegate, as shown in this example.
And another amusing example:
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
public class GradieltButton {
public static void main(String[] args) {
Object grad = UIManager.get("Button.gradient");
List gradient;
if (grad instanceof List) {
gradient = (List) grad;
System.out.println(gradient.get(0));
System.out.println(gradient.get(1));
System.out.println(gradient.get(2));
System.out.println(gradient.get(3));
System.out.println(gradient.get(4));
//gradient.set(2, new ColorUIResource(Color.blue));
//gradient.set(3, new ColorUIResource(Color.YELLOW));
//gradient.set(4, new ColorUIResource(Color.GREEN));
//gradient.set(2, new ColorUIResource(221, 232, 243));//origal Color
//gradient.set(2, new ColorUIResource(255, 255, 255));//origal Color
//gradient.set(2, new ColorUIResource(184, 207, 229));//origal Color
gradient.set(2, new ColorUIResource(190, 230, 240));
gradient.set(3, new ColorUIResource(240, 240, 240));
gradient.set(4, new ColorUIResource(180, 200, 220));
//UIManager.put("Button.background", Color.pink);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GradieltButton().makeUI();
}
});
}
public void makeUI() {
JButton button = new JButton("Click");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
@ShaggyInjun wrote For some reason my UIManager.get("Button.gradient") returns a null. Would you know why ? I know I am using MetalTheme.
this Key in UIManager
returns ColorUIResource
(more in UIManagerDefaults by @camickr)
[0.3, 0.0, javax.swing.plaf.ColorUIResource[r=221,g=232,b=243], javax.swing.plaf.ColorUIResource[r=255,g=255,b=255], javax.swing.plaf.ColorUIResource[r=184,g=207,b=229]]
is required to use ColorUIResource
instead of Gradient
, Button.gradien
t returns arrays of Colors and Insets
== ColorUIResource