Implementing Variable-Height Column Headers in a JTable Component - Java Swing

Java examples for Swing:JTable Column

Description

Implementing Variable-Height Column Headers in a JTable Component

Demo Code

import java.awt.Component;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

public class Main {
  public static void main(String[] args) {
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);

    model.addColumn("Col1");
    model.addColumn("Icon Here");

    int vColIndex = 1;
    table.getColumnModel().getColumn(vColIndex).setHeaderValue(
        new ImageIcon("image.gif"));

    TableCellRenderer iconHeaderRenderer = new DefaultTableCellRenderer() {
        public Component getTableCellRendererComponent(JTable table, Object value,
                     boolean isSelected, boolean hasFocus, int row, int column) {
            // Inherit the colors and font from the header component
            if (table != null) {
                JTableHeader header = table.getTableHeader();
                if (header != null) {
                    setForeground(header.getForeground());
                    setBackground(header.getBackground());
                    setFont(header.getFont());
                }//from  w  w  w.  j a v  a2 s .  co m
            }

            if (value instanceof Icon) {
                // Value is an Icon
                setIcon((Icon)value);
                setText("");
            } else {
                // Value is text
                setText((value == null) ? "" : value.toString());
                setIcon(null);
            }
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            setHorizontalAlignment(JLabel.CENTER);
            return this;
        }
    };

    // Finally, set the icon header renderer on the second column
    table.getColumnModel().getColumn(vColIndex)
        .setHeaderRenderer(iconHeaderRenderer);
  }
}

Related Tutorials