How to set a tooltip to each column of a JTableHeader in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JTableHeader is a subclass of JComponent class, When we create a JTable object, the constructor creates a new JTableHeader object to manage the table component's header. A JTable supplies a setTableHeader() method that establishes the table header component's JTableHeader object and a getTableHeader() method that returns a reference to the table header component's JTableHeader object. We can set a tooltip text to each column of a JTableHeader by overriding the getToolTipText() method of JTableHeader class.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableHeaderToolTipTest extends JPanel {
   private DefaultTableModel dmodel;
   private JTable table;
   private JScrollPane jsp;
   public JTableHeaderToolTipTest() {
      setLayout(new BorderLayout());
      String[] headers = {"Name", "Age", "Contact Number", "City"};
      String[] toolTips = {"Name of Emp", "Age of Emp", "Contact Number of Emp","City of Emp"};
      dmodel = new DefaultTableModel(headers, 4);
      table = new JTable(dmodel);
      ToolTipHeader tooltipHeader = new ToolTipHeader(table.getColumnModel());
      jsp = new JScrollPane(table);
      add(jsp, BorderLayout.CENTER);
   public static void main(String[] args) {
      JFrame frame = new JFrame("JTableHeaderToolTip Test");
      frame.getContentPane().add(new JTableHeaderToolTipTest(), BorderLayout.CENTER);
      frame.setSize(400, 250);
// implementation code to set a tooltip text to each column of JTableHeader
class ToolTipHeader extends JTableHeader {
   String[] toolTips;
   public ToolTipHeader(TableColumnModel model) {
   public String getToolTipText(MouseEvent e) {
      int col = columnAtPoint(e.getPoint());
      int modelCol = getTable().convertColumnIndexToModel(col);
      String retStr;
      try {
         retStr = toolTips[modelCol];
      } catch (NullPointerException ex) {
         retStr = "";
      } catch (ArrayIndexOutOfBoundsException ex) {
         retStr = "";
      if (retStr.length() < 1) {
         retStr = super.getToolTipText(e);
      return retStr;
   public void setToolTipStrings(String[] toolTips) {
      this.toolTips = toolTips;


Updated on 10-Feb-2020 10:46:28