更改JButton渐变颜色,但仅适用于一个按钮,而不是全部 [英] Change JButton gradient color, but only for one button, not all

查看:241
本文介绍了更改JButton渐变颜色,但仅适用于一个按钮,而不是全部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改 JButton 渐​​变色,
i找到这个, http://java2everyone.blogspot.com/2009/01/set-jbutton-gradient-color.html ,但我想更改渐变只有一个按钮,而不是所有按钮

I want to change JButton gradient color, i found this, http://java2everyone.blogspot.com/2009/01/set-jbutton-gradient-color.html, but i want to change gradient for only one button, not all button

推荐答案

您可以覆盖 JButton的com / javase / 6 / docs / api / javax / swing / JComponent.html#paintComponent%28java.awt.Graphics%29rel =nofollow noreferrer> paintComponent 方法实例并绘制其图形具有以下类之一的对象实现绘画界面:

You can override the paintComponent method of the JButton instance and paint its Graphics object with one of the following classes that implement the Paint interface:

  • GradientPaint.
  • LinearGradientPaint
  • MultipleGradientPaint
  • RadialGradientPaint
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 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(JGradientButton.newInstance());
        frame.setSize(new Dimension(300, 150)); // used for demonstration
        //frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static class JGradientButton extends JButton {
        private JGradientButton() {
            super("Gradient Button");
            setContentAreaFilled(false);
            setFocusPainted(false); // used for demonstration
        }

        @Override
        protected void paintComponent(Graphics g) {
            final Graphics2D g2 = (Graphics2D) g.create();
            g2.setPaint(new GradientPaint(
                    new Point(0, 0), 
                    Color.WHITE, 
                    new Point(0, getHeight()), 
                    Color.PINK.darker()));
            g2.fillRect(0, 0, getWidth(), getHeight());
            g2.dispose();

            super.paintComponent(g);
        }

        public static JGradientButton newInstance() {
            return new JGradientButton();
        }
    }
}

这篇关于更改JButton渐变颜色,但仅适用于一个按钮,而不是全部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆