Creating a Custom Column Header Renderer in a JTable Component - Java Swing

Java examples for Swing:JTable Column

Description

Creating a Custom Column Header Renderer in a JTable Component

Demo Code


import java.awt.Component;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main {
  public static void main(String[] argv) {
    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());
  }/*from  w  ww .  j  a  v a  2  s  .c  om*/

}

class MyTableHeaderRenderer extends JLabel implements TableCellRenderer {
  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {

    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) {
  }
}

Related Tutorials