Setting Column Header Tool Tips in a JTable Components

To display a tool tip for a column header, install a mouse motion listener on the header component and change its tool tip based on which column header is under the cursor.
int rows = 10; int cols = 5; JTable table = new JTable(rows, cols); JTableHeader header = table.getTableHeader(); ColumnHeaderToolTips tips = new ColumnHeaderToolTips(); // Assign a tooltip for each of the columns for (int c=0; c<table.getColumnCount(); c++) { TableColumn col = table.getColumnModel().getColumn(c); tips.setToolTip(col, "Col "+c); } header.addMouseMotionListener(tips); public class ColumnHeaderToolTips extends MouseMotionAdapter { // Current column whose tooltip is being displayed. // This variable is used to minimize the calls to setToolTipText(). TableColumn curCol; // Maps TableColumn objects to tooltips Map tips = new HashMap(); // If tooltip is null, removes any tooltip text. public void setToolTip(TableColumn col, String tooltip) { if (tooltip == null) { tips.remove(col); } else { tips.put(col, tooltip); } } public void mouseMoved(MouseEvent evt) { TableColumn col = null; JTableHeader header = (JTableHeader)evt.getSource(); JTable table = header.getTable(); TableColumnModel colModel = table.getColumnModel(); int vColIndex = colModel.getColumnIndexAtX(evt.getX()); // Return if not clicked on any column header if (vColIndex >= 0) { col = colModel.getColumn(vColIndex); } if (col != curCol) { header.setToolTipText((String)tips.get(col)); curCol = col; } } }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.