How to add a Gradient Background to any JComponent

GradientBackground1Almost every “web 2.0″ application have a cool linear gradient background instead of the plain old boring single color solid background. Adding a gradient background to your application is very simple with only a few lines of additional code. In the example program, I am using Java2D and the GradientPaint class to draw the linear gradient background.

Below is the program that I used to create the image above. We override the paintComponent of the JPanel (or any JComponent) and fill the background with a gradient paint. The begin and end colors for the gradient paint are derived from the component’s background color using the brighter and darker variations.

The one important step is to set the component to be non-opaque using the setOpaque(false) method. This will prevents Swing from painting the background, because we want to control the background painting ourselves. If the component was opaque, then Swing will overwrite our gradient background with a solid background when we call super.paintComponent(g) in our implement implementation of paintComponent.


Enter your email below to download the source code.


Posted in Design, Java Swing and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>