2011-03-31 41 views
1

我有一個JTable顯示Java Swing應用程序中的一些記錄。用戶只能使用整行,而不是單個單元。有什麼辦法可以專注於JTable的整行?默認設置是隻關注用戶點擊的單元格。我爲焦點使用了不同的顏色,所以如果只有一個細胞聚焦而不是整行,它看起來不太好。如何關注一整行JTable?

UPDATE:這是我目前我的自定義TableCellRenderer的代碼,問題是,當行具有焦點,並繪有「焦點訪談」的顏色,然後JTable失去焦點,只有細胞那焦點重新用「選定」顏色重新繪製,但選定行中的所有單元格都應使用「選定」顏色重新繪製。

@Override 
public Component getTableCellRendererComponent(JTable table, 
     Object value, boolean isSelected, boolean hasFocus, 
     int row, int column) { 

    // Has any cell in this row focus? 
    if(table.getSelectedRow() == row && table.hasFocus()) { 
     hasFocus = true; 
    } 

    if (hasFocus) { 
     this.setBackground(CustomColors.focusedColor); 
    } else if (isSelected) { 
     this.setBackground(CustomColors.selectedColor); 
    } else { 

     // alternate the color of every second row 
     if(row % 2 == 0) { 
      this.setBackground(Color.WHITE); 
     } else { 
      this.setBackground(CustomColors.grayBg); 
     } 
    } 

    setValue(value); 

    return this; 

} 
+0

是否足以使用自定義cellrenderer來顯示行中的所有單元格,因爲它們將具有焦點? – Howard 2011-03-31 16:39:15

+0

@霍華德:是的,如果你有建議,那就足夠了。 – Jonas 2011-03-31 16:48:05

+0

另請參閱[表格行渲染](http://tips4java.wordpress.com/2010/01/24/table-row-rendering/)。 – trashgod 2011-04-01 02:57:40

回答

2

聽起來像是你在找the setRowSelectionAllowed() method

既然你說過只是改變顏色就足夠了,你可能想看看Swing教程的custom cell renderer section。您只需設置邏輯以檢查給定單元格是否位於選定行中,並相應地繪製背景顏色。

+0

沒關係,我在考慮選擇,而不是專注。 – Pops 2011-03-31 16:44:20

+0

這是一個很好的建議,但我有一個問題。當JTable失去焦點時,只有被聚焦的單元格被重新繪製(使用「selected」顏色),並且該行上的其他單元格仍然具有「聚焦」的顏色,因爲它們沒有被重新繪製。有什麼建議麼? – Jonas 2011-03-31 17:16:20

+0

@Jonas,讓渲染器明確地設置所有不在選定行的單元格上的「普通」背景顏色,而不是忽略它們。 – Pops 2011-03-31 17:24:06

1

第一個想法是像

JTable jTable = new JTable() { 
    public TableCellRenderer getCellRenderer(int row, int column) { 
     final TableCellRenderer superRenderer = super.getCellRenderer(row, column); 
     return new TableCellRenderer() { 

      @Override 
      public Component getTableCellRendererComponent(JTable table, Object object, boolean isSelected, boolean hasFocus, int row, int column) { 
       // determine focus on row attribute only 
       hasFocus = hasFocus() && isEnabled() && getSelectionModel().getLeadSelectionIndex() == row; 
       return superRenderer.getTableCellRendererComponent(table, object, isSelected, hasFocus, row, column); 
      } 
     }; 
    } 
}; 

,我用我自己的邏輯來確定基於行的焦點只讀屬性。它使用基礎的單元格渲染器,但使用焦點邊框時看起來很奇怪。

+0

謝謝,但我認爲這與我在我更新的問題中發佈的代碼具有相同的問題。當'JTable'失去焦點時,只有具有焦點的單元格被重新繪製。所以行中的其他單元格仍將具有「焦點」顏色。 – Jonas 2011-03-31 17:34:29