/**
* Created by IntelliJ IDEA.
* User: hufeng
* Date: Jul 14, 2004
* Time: 11:06:52 AM
* To change this template use Options | File Templates.
*/
public class TableExample {
public static void main(String args[])
{
JFrame j = new TableExampleJFrame();
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.show();
}
}
class TableExampleJFrame extends JFrame
{
public TableExampleJFrame()
{
setSize(300,300);
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("a.gif")));
JScrollPane pane = new JScrollPane(table);
Container c = getContentPane();
c.add(pane,BorderLayout.CENTER);
}
// 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());
}
}