Search code examples
javajtabletooltiptablecellrenderer

Show tooltips in JTable only when column is cut off


how can I implement a tooltip which shows me for each cell a tip when the value is too long?

I just have a table renderer which colors me some cell. So I think the easiest way is to implement the metod in it.

public class ColorRenderer extends DefaultTableCellRenderer {

      final int STATUS_COL = 7;

      @Override
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean
     hasFocus,
      int row, int col) {

      Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

     int modelIndex = table.convertRowIndexToModel(row);
      String type = (String) table.getModel().getValueAt(modelIndex, 7);

      if ("".endsWith(type)) {
      component.setBackground(table.getBackground());
      component.setForeground(table.getForeground());


      } else {
      component.setBackground(Color.RED);
      component.setForeground(Color.WHITE);

      }
      if (isSelected) {
      setBackground(table.getSelectionBackground());
      setForeground(table.getSelectionForeground());

      }

      return component;
      }

}

Thank you in advance.


Solution

  • Start by overriding the getToolTipText(MouseEvent) event of the JTable.

    public String getToolTipText(MouseEvent e) {
        String toolTipText = null;
    

    Get the cell coordinates for the given mouse location...

    Point p = e.getPoint(); // MouseEvent
    int col = columnAtPoint(p);
    int row = rowAtPoint(p);
    

    Get the cells current size, this way we know what the current constraints are...

    Rectangle bounds = getCellRect(row, col, false);
    

    Get the renderer for the cell, based on the current value for the cell from the model...

    Object value = getValueAt(row, col);
    Component comp = prepareRenderer(getCellRenderer(row, col), row, col);
    

    Compare the preferred size of the renderer component against the cell size...

    if (comp.getPreferredSize().width > bounds.width) {
        toolTipText = comp.getToolTipText();
    }
    

    Return the tool tip...

        return toolTipText;
    }