简体   繁体   English

如何向JTable的行添加工具提示

[英]How to add tooltips to JTable's rows

how can I add tooltips to JTable's rows (Java Swing)? 如何将工具提示添加到JTable的行(Java Swing)? These tooltips should contain same values of the relative row. 这些工具提示应包含相对行的相同值。

This is the code I used in my class that extends JTable. 这是我在我的类中使用的扩展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): 它覆盖了方法“prepareRenderer”,但是我得到了空单元格,它为行内的每个单元格添加了一个工具提示,而不是整行的一个工具提示(这就是我正在寻找的):

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. 设置工具提示的另一种方法是覆盖JTable的getToolTipText(MouseEvent)方法。 Then you can use the rowAtPoint(...) method of the table to get the row and then return the appropriate tool tip for the row. 然后,您可以使用表的rowAtPoint(...)方法获取行,然后返回该行的相应工具提示。

Just use below code while creation of JTable object. 在创建JTable对象时使用下面的代码。

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. rowIndex可以是ZERO。

change: 更改:

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

by: 通过:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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