Shading Columns in JTable

In this section, you will learn how to shading column in JTable.

Shading Columns in JTable


Earlier you have read about the shading of  the rows in JTable. So, you are now capable for setting the shading the column in JTable.  In JTable component the shading columns are the simplest way of shading alternate columns in JTablecomponent that overrides the prepareRenderer() method. The following code helps you for setting the shading columns in JTable.

Description of program:

First of all the given code creates a table with specified column with headers by using JTableHeader that contains some data in it. The background color of the column header is yellow and the text color is black. After this, you need to shade the alternate columns (Odd place's row) in JTable component that overrides the prepareRenderer() method. The table calls the prepareRenderer method for every cell that is used to display and override method calls the super class and retrieves the prepareRenderer components. Then you have to get a colorful column of JTable.

Here is the code of program:

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class SaddingColumns{
  public static void main(String[] args) {
  new SaddingColumns();
  public SaddingColumns(){
  JFrame frame = new JFrame("Sadding Columns in a JTable");
  JPanel panel = new JPanel();
  String data[][] {{"100","Vinod","programmer","5000"},
"101","Deepak","Content Writer","20000"},
"102","Noor","Techniqual Writer","30000"},{"104","Rinku","PHP programar","25000"}};
  String col[] {"Emp_Id","Emp_name","Emp_depart","Emp_sal"};
  DefaultTableModel model = new DefaultTableModel(data,col);
  //Setting the sadding in column
  JTable table = new JTable(model){
  public Component prepareRenderer
TableCellRenderer renderer, int index_row, int index_col){
  Component comp = super.prepareRenderer(renderer, index_row, index_col);
  //odd col index, selected or not selected
  if(index_col % != && !isCellSelected(index_row, index_col)){
  return comp;
  JTableHeader header = table.getTableHeader();
  JScrollPane pane = new JScrollPane(table);

Download this example.

Share on Google+Share on Google+

Shading Columns in JTable

Posted on: April 14, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Shading Columns in JTable  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image