Google Tag Manager

2015/12/01

Show JToolTip for Icons placed in the cell of the JTable

Code

private final JTable table = new JTable(model) {
  @Override public String getToolTipText(MouseEvent e) {
    Point pt = e.getPoint();
    int vrow = rowAtPoint(pt);
    int vcol = columnAtPoint(pt);
    //int mrow = convertRowIndexToModel(vrow);
    int mcol = convertColumnIndexToModel(vcol);
    if (mcol == 1) {
      TableCellRenderer tcr = getCellRenderer(vrow, vcol);
      Component c = prepareRenderer(tcr, vrow, vcol);
      if (c instanceof JPanel) {
        Rectangle r = getCellRect(vrow, vcol, true);
        c.setBounds(r);
        //@see http://stackoverflow.com/questions/10854831/tool-tip-in-jpanel-in-jtable-not-working
        c.doLayout();
        pt.translate(-r.x, -r.y);
        Component l = SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y);
        if (l instanceof JLabel) {
          ImageIcon icon = (ImageIcon)((JLabel) l).getIcon();
          return icon.getDescription();
        }
      }
    }
    return super.getToolTipText(e);
  }
};
class ListIconRenderer implements TableCellRenderer {
  private final JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
    p.removeAll();
    if (isSelected) {
      p.setOpaque(true);
      p.setBackground(table.getSelectionBackground());
    } else {
      p.setOpaque(false);
    }
    if (value instanceof List) {
      for (Object o : (List) value) {
        if (o instanceof Icon) {
          Icon icon = (Icon) o;
          JLabel label = new JLabel(icon);
          label.setToolTipText(icon.toString());
          p.add(label);
        }
      }
    }
    return p;
  }
}

References

No comments:

Post a Comment