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.

Example

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());
      tooltipHeader.setToolTipStrings(toolTips);
      table.setTableHeader(tooltipHeader);
      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);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
// implementation code to set a tooltip text to each column of JTableHeader
class ToolTipHeader extends JTableHeader {
   String[] toolTips;
   public ToolTipHeader(TableColumnModel model) {
      super(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;
   }
}

Output

raja
Published on 26-Jul-2019 12:54:57
Advertisements