![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e933. Displaying an Icon in a Column Head of a JTable ComponentAlthough the default renderer for a table header is aJLabel , 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; } };
e932. Changing the Name of a Column in a JTable Component e934. Implementing Variable-Height Column Headers in a JTable Component e935. Removing the Column Headers from a Scrollable in a JTable Component e936. Creating a Custom Column Header Renderer in a JTable Component
© 2002 Addison-Wesley. |