2011-11-30 69 views
7

如何將工具提示添加到JTable的行(Java Swing)? 這些工具提示應該包含相對行的相同值。如何將工具提示添加到JTable的行

這是我在我的課程中使用的擴展JTable的代碼。它覆蓋的方法「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; 
} 
+1

您是否需要補償和jcomp之間的比較?我認爲它要麼永遠工作,要麼永遠不會工作...... – BenCole

+0

「相對行的相同值」這是什麼意思? – kleopatra

回答

14

它增加了一個工具提示行內各單體電池,而不是一個提示爲全行

你正在改變取決於行和列的提示。如果您只希望工具提示按行更改,那麼我只會檢查行值並忘記列值。

另一種設置工具提示的方法是覆蓋JTable的getToolTipText(MouseEvent)方法。然後,您可以使用表格的rowAtPoint(...)方法獲取該行,然後返回該行的相應工具提示。

+1

謝謝你幾乎完美!唯一缺少的是,該工具提示現在持續幾秒鐘。我想保持它顯示,直到鼠標指針移開。那可能嗎? – Randomize

+3

這由「ToolTipManager」控制。您可以更改解僱值。 – camickr

2

請參閱JComponent.setToolTipText() - 您希望每行數據的JComponent是而不是該表,而是數據的單元格渲染器,可以爲每個渲染的單元格配置JComponent。

+0

感謝您的回答。我用更多的信息編輯了我的問題。 – Randomize

5

只需在創建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; 
      } 
     }; 
0

rowIndex可以爲零。

變化:

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

由:

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