Displaying an Icon in a Column Head of a JTable Component

Although the default renderer for a table header is a JLabel, the default renderer will only display text. This example demonstrates how to install a custom renderer that can display text as well as icons.
DefaultTableModel model = new DefaultTableModel(); JTable table = new JTable(model); // Create 2 columns model.addColumn("Col1"); model.addColumn("Col2"); // the header value for this column will be overwritten // with a TextandIcon object // Set the icon renderer on the second column table.getTableHeader().getColumnModel() .getColumn(1).setHeaderRenderer(iconHeaderRenderer); // Set the text and icon values on the second column for the icon render table.getColumnModel().getColumn(1).setHeaderValue( new TextAndIcon("Col2", new ImageIcon("icon.gif"))); // This class is used to hold the text and icon values // used by the renderer that renders both text and icons class TextAndIcon { TextAndIcon(String text, Icon icon) { this.text = text; this.icon = icon; } String text; Icon icon; } // This customized renderer can render objects of the type TextandIcon 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()); } } if (value instanceof TextAndIcon) { setIcon(((TextAndIcon)value).icon); setText(((TextAndIcon)value).text); } else { setText((value == null) ? "" : value.toString()); setIcon(null); } setBorder(UIManager.getBorder("TableHeader.cellBorder")); setHorizontalAlignment(JLabel.CENTER); return this; } };

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.