How to set tooltip to JTable cell?

We have already seen how to create a simple jtable using simple jtable model in java swing. In this article we will see how we can show the tooltip in jtable cell in java swing.

How to set tooltip to JTable cell

As we all know tool tips are now most important part of the graphical user interface design. In case of JTable, it can happen that cell values are larger than the cell width. so in this case we need to add tool tip to each cell. When a mouse or cursor goes on the cell, cell value should get displayed. In this example of jtable cell tool tip we will see how we can set the tooltip to each cell.

With the help of example source code you can easily set the tool tip on jtable cell. For this as shown in the code below we need to create one JTable component. Next and very important step is to override prepareRenderer() method to get the renderer component on which we need to set the tooltip. We are type casting the object to JComponent to set the tooltip. To set the tooltip we are using setToolTipsText(String str): method.

Example for setting tool tip on JTable cell

public class JTableCellToolTip {

static JTable tableCellToolTip;

public static void main(String[] args) {

JFrame frameWithJTable = new JFrame( "JTable cell tool tip example" );

frameWithJTable.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

JPanel panel = new JPanel();

String data[][] = {{"Mark", "Physics", "88"},

{"John", "Maths", "82"},

{"Alex", "Biology", "93"},

{"Nathan", "Chemistry", "95"}};

String col[] = {"Name", "Subject", "Marks"};

DefaultTableModel model = new DefaultTableModel( data, col );

tableCellToolTip = new JTable(model) {

public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {

Component comp = super.prepareRenderer(renderer, row, col);

JComponent jcomp = (JComponent) comp;

if (comp == jcomp) {

jcomp.setToolTipText((String) getValueAt(row, col));


return comp;



JTableHeader header = tableCellToolTip.getTableHeader();

header.setBackground( Color.MAGENTA );

JScrollPane pane = new JScrollPane( tableCellToolTip );

panel.add( pane );

frameWithJTable.add( panel );

frameWithJTable.setSize( 520, 170 );

frameWithJTable.setVisible( true );



Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment