如何为JButton设置自定义渐变?

时间:2012-10-05 15:24:54

标签: java swing

我想做的事情与this完全相同,但只为我需要的一个或两个按钮设置自定义渐变,而不是为所有JButton实例设置。并动态设置/取消设置 - 例如按钮选择/未选择模式。

2 个答案:

答案 0 :(得分:1)

所以,这是答案。

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

    class JGradientButton extends JButton{
        Color color1 = Color.WHITE;
        Color color2 = Color.PINK;
        JGradientButton(){
            super("Gradient Button");
            setContentAreaFilled(false);
            setFocusPainted(false); // used for demonstration
            addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent evt) {
                    color2 = (color2==Color.PINK) ? Color.GREEN : Color.PINK;
                    //System.out.println(button.isSelected());
                }
            });

        }

        @Override
        protected void paintComponent(Graphics g){
            Graphics2D g2 = (Graphics2D)g.create();
            g2.setPaint(new GradientPaint(
                    new Point(0, 0), 
                    color1, 
                    new Point(0, getHeight()), 
                    color2));
            g2.fillRect(0, 0, getWidth(), getHeight());
            g2.dispose();

            super.paintComponent(g);
        }


    }

和...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public final class JGradientButtonDemo {
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();         
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame("Gradient JButton Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.add(new JGradientButton());
        frame.setSize(new Dimension(300, 150)); // used for demonstration
        //frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }


}

答案 1 :(得分:1)

我修改了scythargon的答案并创建了一个简单而高级的渐变按钮。

enter image description here

import java.awt.*;
import javax.swing.*;

public class ButtonGradientTest {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                createAndShowGUI();
            }
        });
    }

    protected static void createAndShowGUI() {
        JFrame  frame   = new JFrame("Button Color Test");
        JPanel  panel1  = new JPanel(new FlowLayout());
        JPanel  panel2  = new JPanel(new FlowLayout());
        JButton button1 = new JGradientButtonSimple("Simple", Color.RED, Color.ORANGE);
        JButton button2 = new JGradientButton("Advanced", Color.GREEN, Color.BLUE);

        button1.setPreferredSize(new Dimension(100, 100));
        button1.setForeground(Color.YELLOW);
        button2.setPreferredSize(new Dimension(100, 100));
        button2.setForeground(Color.MAGENTA);

        panel1.add(button1);
        panel2.add(button2);
        frame.add(panel1, BorderLayout.WEST);
        frame.add(panel2, BorderLayout.EAST);

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

简单渐变

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class JGradientButtonSimple extends JButton {
    private static final long serialVersionUID = 1L;
    private Color stopTop;
    private Color stopBottom;
    private Paint colorGradient;
    private Point[] stopPoints = new Point[2];

    public JGradientButtonSimple(Color stopTop, Color stopBottom) {
        this("", stopTop, stopBottom);
    }

    public JGradientButtonSimple(String text, Color stopTop, Color stopBottom) {
        this(text, null, stopTop, stopBottom);
    }

    public JGradientButtonSimple(String text, Icon icon, Color stopTop, Color stopBottom) {
        super(text, icon);

        setContentAreaFilled(false);
        setFocusPainted(false);

        this.stopTop = stopTop;
        this.stopBottom = stopBottom;

        addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                invalidate();
            }
        });
    }

    public void invalidate() {
        super.invalidate();

        stopPoints[0] = new Point(0, 0);
        stopPoints[1] = new Point(0, getHeight());

        if (getModel().isPressed()) {
            colorGradient = new GradientPaint(stopPoints[0], stopBottom, stopPoints[1], stopTop);
        } else {
            colorGradient = new GradientPaint(stopPoints[0], stopTop, stopPoints[1], stopBottom);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();

        g2.setPaint(colorGradient);
        g2.fillRect(0, 0, getWidth(), getHeight());
        g2.dispose();

        super.paintComponent(g);
    }
}

高级渐变

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class JGradientButton extends JButton {
    private static final long serialVersionUID = 1L;
    private Color[] stops = new Color[2];
    private Paint colorGradients[] = new Paint[2];
    private Point[] stopPoints = new Point[3];

    public JGradientButton(Color stopTop, Color stopBottom) {
        this("", stopTop, stopBottom);
    }

    public JGradientButton(String text, Color stopTop, Color stopBottom) {
        this(text, null, stopTop, stopBottom);
    }

    public JGradientButton(String text, Icon icon, Color stopTop, Color stopBottom) {
        super(text, icon);

        setContentAreaFilled(false);
        setFocusPainted(false);

        stops[0] = stopTop;
        stops[1] = stopBottom;

        addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                invalidate();
            }
        });
    }

    public void invalidate() {
        super.invalidate();

        stopPoints[0] = new Point(0, 0);
        stopPoints[1] = new Point(0, (int) (getHeight() * 0.33));
        stopPoints[2] = new Point(0, (int) (getHeight() * 1.00));

        int stop = getModel().isPressed() ? 1 : 0;
        Color highlight = stop == 0 ? Color.WHITE : Color.BLACK;

        colorGradients[0] = new GradientPaint(stopPoints[0], stops[stop], stopPoints[1], highlight);
        colorGradients[1] = new GradientPaint(stopPoints[1], highlight, stopPoints[2], stops[1 - stop]);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();

        for (int i = 0, offset = getHeight() / stopPoints.length; i < colorGradients.length; i++) {
            g2.setPaint(colorGradients[i]);
            g2.fillRect(0, i * offset, getWidth(), getHeight() - (i * offset));
        }
        g2.dispose();

        super.paintComponent(g);
    }
}