Author: Zafir Anjum
Display an image (along with the text label) in the header. Actually the code below displays a JButton. It uses a custom cell renderer to do that. In fact, you could use any other JComponent (JLabel is a good candidate) instead of a JButton but you might have to massage the component a bit more. If you use a JLabel, you'll have to take care of the border yourself.
Note the call to table.revalidate(). This call is required otherwise you may not see the change immediately.
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Table
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Table");
frame.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
Window win = e.getWindow();
win.setVisible(false);
win.dispose();
System.exit(0);
}
} );
//JTable table = new JTable( 4, 5 );
JTable table = new JTable( new String[][]{{"r0c0", "r0c1"},{"r1c0", "r1c1"}}, new String[]{"First", "Second"} );
table.setRowSelectionAllowed( false );
JScrollPane sp = new JScrollPane(table);
frame.getContentPane().add( sp );
frame.pack();
frame.show();
JButton b1 = new JButton( "Column 1", new ImageIcon( "new.gif" ) );
JButton b2 = new JButton( "Column 2", new ImageIcon( "new.gif" ) );
table.getColumnModel().getColumn(0).setHeaderRenderer( new JComponentCellRenderer() );
table.getColumnModel().getColumn(1).setHeaderRenderer( new JComponentCellRenderer() );
table.getColumnModel().getColumn(0).setHeaderValue( b1 );
table.getColumnModel().getColumn(1).setHeaderValue( b2 );
table.getTableHeader().revalidate();
}
}
class JComponentCellRenderer implements TableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return (JComponent)value;
}
}
Posted On: 9-Jan-1999