开发者

repaint swing button with different gradient

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜