Gradient JPanel Backgrounds
Using gradient backgrounds in your application creates a clean and polished look. Doing so can really help improve the interface without too much effort.
The Code
Add the following overridden method to your JPanel to create a gradient background from top-to-bottom. In this example, the gradient goes from a darker color to a lighter color (darker on the top, lighter on the bottom).
@Override
protected void paintComponent( Graphics g ) {
if ( !isOpaque( ) ) {
super.paintComponent( g );
return;
}
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
Color color1 = getBackground();
Color color2 = color1.brighter();
GradientPaint gp = new GradientPaint( 0, 0, color1, 0, h, color2 );
g2d.setPaint( gp );
g2d.fillRect( 0, 0, w, h );
setOpaque( false );
super.paintComponent( g );
setOpaque( true );
}
Initialization
Remember to set the initial background color of the JPanel elsewhere, because we take the first color of the gradient from the JPanel background. Normally this is done in the initialization.
E.g. in your panel’s initialization method, you should set the background like so:
// Change this to whatever color your prefer this.setBackground(new Color(174, 214, 232)); // Light blue
Flipping Colors
It’s easy to flip the colors so that you go from light-to-dark or dark-to-light. In line 16 of the above code, we have:
Color 2 = color1.brighter();
To make the gradient go from light-to-dark, you could change this to:
Color 2 = color1.darker();
Opaqueness
More than likely, you’ll have other components on top of this panel. You’ll need to add setOpaque( false ) to each component to ensure that their backgrounds are see-thru, otherwise by default you’ll see an ugly gray box around everything.
An Example
To view an example of a gradient background applied to a JPanel, check out my post on a Klondike game I made which contains a screenshot.
