JAVA vertical gradient background panel

Recently i had to create a gradient background for one of the panels in our [POS application](http://inforviegas.pt/wp-content/uploads/2010/09/VOS.jpg), so i though i'd share the code.

You need to pass the top and bottom colors of the gradient and also make sure that any panels inside this one are transparent (i.e. setOpaque(false)), otherwise they will paint above it.

import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints;

import javax.swing.JPanel;

public class VerticalGradientBackgroundPanel extends JPanel {

private Color topColor; private Color bottomColor;

public VerticalGradientBackgroundPanel(Color topColor, Color bottomColor) {

this.topColor = topColor; this.bottomColor = bottomColor; }

@Override protected void paintComponent(Graphics grphcs) {

super.paintComponent(grphcs);

Graphics2D g2d = (Graphics2D) grphcs;

g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GradientPaint gp = new GradientPaint(0, 0, topColor, 0, getHeight(), bottomColor); g2d.setPaint(gp); g2d.fillRect(0, 0, getWidth(), getHeight()); } }