How to add tooltips to JTable's rows

2019-01-15 19:04发布

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;
}

4条回答
smile是对你的礼貌
2楼-- · 2019-01-15 19:29

see JComponent.setToolTipText() -- the JComponent you want on per-row data is not the table, but rather the cell renderer of the data, which has access to configuring a JComponent for each rendered cell.

查看更多
女痞
3楼-- · 2019-01-15 19:30

rowIndex can be ZERO.

change:

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

by:

if(rowIndex >= 0){
   tip = getValueAt(rowIndex, colIndex).toString();
}
查看更多
We Are One
4楼-- · 2019-01-15 19:49

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;
            }
        };
查看更多
Lonely孤独者°
5楼-- · 2019-01-15 19:52

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.

查看更多
登录 后发表回答