简体   繁体   中英

How to add tooltips to JTable's rows

how can I add tooltips to JTable's rows (Java Swing)? These tooltips should contain same values of the relative row.

This is the code I used in my class that extends JTable. It overrides the method "prepareRenderer", but I got empty cells, and it adds a tooltip for each single cell within row, not one tooltip for the whole row (that is what I'm looking for):

public Component prepareRenderer(TableCellRenderer renderer,int row, int col) {
    Component comp = super.prepareRenderer(renderer, row, col);
    JComponent jcomp = (JComponent)comp;
    if (comp == jcomp) {
        jcomp.setToolTipText((String)getValueAt(row, col));
    }
    return comp;
}

it adds a tooltip for each single cell within row, not one tooltip for the whole row

You are changing the tooltip depending on the row and column. If you only want the tooltip to change by row, then I would only check the row value and forget about the column value.

Another way to set the tooltip is to override the getToolTipText(MouseEvent) method of JTable. Then you can use the rowAtPoint(...) method of the table to get the row and then return the appropriate tool tip for the row.

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 {
                    //comment row, exclude heading
                    if(rowIndex != 0){
                      tip = getValueAt(rowIndex, colIndex).toString();
                    }
                } catch (RuntimeException e1) {
                    //catch null pointer exception if mouse is over an empty line
                }

                return tip;
            }
        };

请参阅JComponent.setToolTipText() - 每行数据所需的JComponent 不是表,而是数据的单元格渲染器,可以访问为每个渲染的单元格配置JComponent。

rowIndex can be ZERO.

change:

if(rowIndex != 0){
   tip = getValueAt(rowIndex, colIndex).toString();
}

by:

if(rowIndex >= 0){
   tip = getValueAt(rowIndex, colIndex).toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM