EarthWeb
Developer.com
Site
windows 2000
visual c++
java
visual basic
javascripts
recommend it
 
Book
thinking in java
 
Interact
forum
guest book
jobs
jokes
what's new

share code
 
Resource
add resource
modify resource
new resource
 

[Internet Jobs]
-----
Java by E-mail:

Get the weekly e-mail highlights on Java!
-----

-

Displaying an image in the header


Author: Zafir Anjum


table header

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

internet.commerce