Thursday, August 25, 2011

How to apply Gradient Color to GUI Components in JAVA

  • It’s always said that first impression is last impression. This quote is also applicable in the field of Software Development. To impress your client you must have a pretty good GUI (Graphical User Interface) especially when that client is not belongs from computer field.
  • So, hereby I am going to share about color management for GUI components. A component with gradient color looks good rather than a solid color.
  • I hope you know about Java Applet. In which we are implementing a ‘paint’ method which draws component on applet screen or on frame. We are going to use that same method here also.
  • This method can be applied to any java GUI component such as JPanel, JButton, JTabbedPane, JToggleButton, JMenu, JMenuItem.

Let’s consider a component JPanel , as it’s a swing component it is preceded by ‘J’.

Generate a java class file and name it as
A code to paste in file.
package pkg;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D; // Imported Libraries
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

public class MyJPanelGradient extends JPanel {
protected void paintComponent( Graphics g ) {
if ( !isOpaque( ) ) {
super.paintComponent( g );

Graphics2D g2d = (Graphics2D) g;

//to get height and width of the component
int w = getWidth();
int h = getHeight();

//generating two colors for gradient pattern
/*parameters are consentration of Red, Blue and Green color in HEX format*/
Color color1 = new Color(0xeb,0xeb,0xeb);
Color color2 = new Color(0xa2,0xbd,0xd8);

/*generating gradient pattern from two colors*/
GradientPaint gp = new GradientPaint( 0, 0, color1, 0, h, color2 );
g2d.setPaint( gp ); //set grdient color to graphics2D object
g2d.fillRect( 0, 0, w, h );//feeling color
setOpaque( false );

//Generating Titleborder
TitledBorder title;
title= BorderFactory.createTitledBorder(new LineBorder(new Color(0,51,204), 2, true), null, javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 16), Color.BLACK);

super.setBorder(title); //appling border to JPanel
super.paintComponent( g );
setOpaque( true );
Beauty of this code: Just drag this class file from the list of project file and drop it on window form or frame. It will directly draw a panel with gradient color and border.

You can change color of gradient pattern by changing the parameter passed in Color.
Gradient pattern can also of different type as shown below

With this same concept you can create class for any component with appropriate changes. Just remember to change super class when you changes the component.
Example: for JButton, class declaration will be:

public class MyGradientJButton extends JButton

For different properties of component you can refer all time favorite Java Docs.