esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

How do I create a JTable with a different background color per column?


The trick is to contrive a custom DefaultTableCellRenderer and apply it to individual columns provided by the table's backing column model. The following snippet demonstrates rendering the first column of the table so it displays with grey background and blue foreground highlighting:

Main.java:


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

public class Main extends JFrame
{
public Main() {
JTable table = new JTable(100, 5);

TableColumn tm = table.getColumnModel().getColumn(0);
tm.setCellRenderer(new ColorColumnRenderer(Color.lightGray, Color.blue));

getContentPane().add(new JScrollPane(table));

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public static void main(String [] args) {
Main main = new Main();
main.setSize(400, 400);
main.setVisible(true);
}
}

/**
* Applied background and foreground color to single column of a JTable
* in order to distinguish it apart from other columns.
*/
class ColorColumnRenderer extends DefaultTableCellRenderer
{
Color bkgndColor, fgndColor;

public ColorColumnRenderer(Color bkgnd, Color foregnd) {
super();
bkgndColor = bkgnd;
fgndColor = foregnd;
}

public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);

cell.setBackground( bkgndColor );
cell.setForeground( fgndColor );

return cell;
}
}




Further Information
Author of answer: Shawn Bolan

Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.