Nowadays, if you are developing a GUI application, it looks more “professional” if your window’s background is gradient (i.e. the background fades from light to dark, or dark to light). This gives your application a more polished look and can greatly improve the interface without much effort. Here’s how to do it…
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 );
} // end method paintComponent
Note #1
Please 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
Note #2
Note that in line 15, we use:
Color 2 = color1.brighter();
You can also change this to:
Color 2 = color1.darker();
in order to make the gradient go from the initial color to a darker color (top to bottom).
Note #3
If you have other components on top of this panel (e.g. a JLabel), you will need to add setOpaque( false ) to that component. If you don’t do this, then the background of that component will probably be gray (non-see-thru).
Questions, comments? Leave them below!
Tags: background, gradient
