1

How can I repaint a JButton with a different gradient when it is clicked. I have overridden the paintComponent(Graphics) method to do the initial paint. Onclick I want to repaint it but I dont want the user to be doing this in the actionperformed event as I want this to be a standalone component.

Any ideas how this can be achieved.

Thanks

Farouk Alhassan
  • 3,780
  • 9
  • 51
  • 74

2 Answers2

8

The easiest approach is to use setPressedIcon(), but you can also override paint() in the ButtonUI delegate, as shown in this example.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
6

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.gradient returns arrays of Colors and Insets == ColorUIResource

mKorbel
  • 109,525
  • 20
  • 134
  • 319