Creating a Custom Column Header Renderer in a JTable Component

The default column header renderer simply display a single line of text. If you need to display something other than this, you will need to build and install your own column header renderer. This example defines a generic renderer and installs it on a column.

See Creating a Custom Cell Renderer in a JTable Component for more information about renderers.

JTable table = new JTable(); // Add data... // Install the custom header renderer on the first visible column int vColIndex = 0; TableColumn col = table.getColumnModel().getColumn(vColIndex); col.setHeaderRenderer(new MyTableHeaderRenderer()); public class MyTableHeaderRenderer extends JLabel implements TableCellRenderer { // This method is called each time a column header // using this renderer needs to be rendered. public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) { // 'value' is column header value of column 'vColIndex' // rowIndex is always -1 // isSelected is always false // hasFocus is always false // Configure the component with the specified value setText(value.toString()); // Set tool tip if desired setToolTipText((String)value); // Since the renderer is a component, return itself return this; } // The following methods override the defaults for performance reasons public void validate() {} public void revalidate() {} protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {} public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {} }

Comments

10 Mar 2010 - 2:04pm by Anonymous (not verified)

Thanks a lot!!! Very useful!

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.