用不同的渐变重绘秋千按钮

Far*_*san 1 java swing jbutton

如何在单击时用不同的渐变重新绘制JButton.我已经覆盖了paintComponent(Graphics)方法来进行初始绘制.Onclick我想要重新绘制它,但我不希望用户在actionperformed事件中执行此操作,因为我希望它是一个独立的组件.

任何想法如何实现这一目标.

谢谢

tra*_*god 8

最简单的方法是使用setPressedIcon(),但您也可以paint()ButtonUI委托中覆盖,如本所示.


mKo*_*bel 5

另一个有趣的例子:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

@ShaggyInjun写道由于某种原因,我的UIManager.get(“ Button.gradient”)返回null。你知道为什么吗?我知道我正在使用MetalTheme。

Key in UIManager返回ColorUIResource@camickr在UIManagerDefaults中更多

[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]]

必须使用ColorUIResource而不是GradientButton.gradient返回arrays of Colors and Insets==ColorUIResource