How to add a tooltip to a cell in a jtable?

前端 未结 3 2095
自闭症患者
自闭症患者 2020-12-29 23:00

I have a table where each row represents a picture. In the column Path I store its absolute path. The string being kinda long, I would like that when I hover the mouse over

相关标签:
3条回答
  • 2020-12-29 23:11

    I assume you didn't write a custom CellRenderer for the path but just use the DefaultTableCellRenderer. You should subclass the DefaultTableCellRenderer and set the tooltip in the getTableCellRendererComponent. Then set the renderer for the column.

    class PathCellRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(
                            JTable table, Object value,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
            JLabel c = (JLabel)super.getTableCellRendererComponent( /* params from above (table, value, isSelected, hasFocus, row, column) */ );
            // This...
            String pathValue = <getYourPathValue>; // Could be value.toString()
            c.setToolTipText(pathValue);
            // ...OR this probably works in your case:
            c.setToolTipText(c.getText());
            return c;
        }
    }
    
    ...
    pathColumn.setCellRenderer(new PathCellRenderer()); // If your path is of specific class (e.g. java.io.File) you could set the renderer for that type
    ...
    
    • Oracle JTable tutorial on tooltips
    0 讨论(0)
  • 2020-12-29 23:12

    You say you store an absolute path in a cell. You are probably using a JLabel for setting absolute path string. Suppose you have a label in your cell, use html tags for expressing tooltip content:

    JLabel label = new JLabel("Bla bla");
    label.setToolTipText("<html><p>information about cell</p></html>");
    

    setToolTipText() can be used for some other Swing components if you are using something other than JLabel.

    0 讨论(0)
  • 2020-12-29 23:13

    Just use below code while creation of JTable object.

    JTable auditTable = new JTable(){
    
                //Implement table cell tool tips.           
                public String getToolTipText(MouseEvent e) {
                    String tip = null;
                    java.awt.Point p = e.getPoint();
                    int rowIndex = rowAtPoint(p);
                    int colIndex = columnAtPoint(p);
    
                    try {
                        tip = getValueAt(rowIndex, colIndex).toString();
                    } catch (RuntimeException e1) {
                        //catch null pointer exception if mouse is over an empty line
                    }
    
                    return tip;
                }
            };
    
    0 讨论(0)
提交回复
热议问题