更改JButton渐变颜色,但仅适用于一个按钮,而不是全部

我想改变JButton渐变颜色,我发现这个, http://java2everyone.blogspot.com/2009/01/set-jbutton-gradient-color.html ,但我想只改变一个按钮的渐变,而不是所有的按钮

您可以覆盖JButton实例的paintComponent方法,并使用以下实现Paint接口的类之一绘制其Graphics对象:

  • 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(); } } } 

在此处输入图像描述

对mre回答有点改进:

在此处输入图像描述

 private static final class JGradientButton extends JButton{ private JGradientButton(String text){ super(text); setContentAreaFilled(false); } @Override protected void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D)g.create(); g2.setPaint(new GradientPaint( new Point(0, 0), getBackground(), new Point(0, getHeight()/3), Color.WHITE)); g2.fillRect(0, 0, getWidth(), getHeight()/3); g2.setPaint(new GradientPaint( new Point(0, getHeight()/3), Color.WHITE, new Point(0, getHeight()), getBackground())); g2.fillRect(0, getHeight()/3, getWidth(), getHeight()); g2.dispose(); super.paintComponent(g); } }