Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Set the JTable

Choose the color of a JTable cell

  • Print
  • Feedback

Page 2 of 2

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.table.TableCellRenderer;
import javax.swing.JFrame;
import javax.swing.JTable;
public class TableCellExample 
{
    public static void main( String[] args ) 
    {
        JTable table = new JTable( new ExampleTableModel() ); 
        TableCellRenderer renderer = new CustomTableCellRenderer();
        try
        {
            table.setDefaultRenderer( Class.forName
               ( "java.lang.Integer" ), renderer );
        }
        catch( ClassNotFoundException ex )
        {
            System.exit( 0 );
        }
        JFrame frame = new JFrame();
        frame.addWindowListener( 
            new WindowAdapter() 
            {
                public void windowClosing(WindowEvent e) 
                {
                    System.exit(0);
                }
            }
        );
        frame.getContentPane().add( table );
        frame.pack();
        frame.setVisible( true );
    }
}


The code snippet table.setDefaultRenderer( Class.forName( "java.lang.Integer" ), renderer ); tells the table to use the custom cell renderer for any cell that contains an integer. You can also set a table's renderer by setting the proper TableColumn object directly.

About the author

Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in the bridging of disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Read more about Core Java in JavaWorld's Core Java section.

  • Print
  • Feedback

Resources