2014-10-02 40 views
0

我已經通過搜索,但似乎找不到一個類似的答案。爪哇JTable - 着色選定的行

我想爲所選行着色並同時永久着色其他行。 即有塔的總總是灰色,但動態地使所選擇的行灰度

我試着

JTable table = new JTable(model) { 
     public Component prepareRenderer(TableCellRenderer renderer, int index_row, int index_col) { 
      Component comp = super.prepareRenderer(renderer, index_row, index_col); 
      //odd col index, selected or not selected 
      if(isCellSelected(index_row, index_col)){ 
       comp.setBackground(Color.GRAY); 
      } 
      if (index_col == 34) { 
       comp.setBackground(Color.GRAY);     
      } else { 
       comp.setBackground(Color.WHITE); 
       setSelectionForeground(Color.BLUE); 

       setSelectionBackground(Color.GRAY); // Thought this would work but has no affect. 
       // comp.setFont(new Font("Serif", Font.BOLD, 12)); 

      } 
      return comp; 
     } 
    }; 

但它不改變所選行的背景顏色,只是全部行。

回答

1

我不確定,但我認爲你需要一個「其他」後面的if (isCellSelected(index_row, index_col)) 塊。這可以解決您的問題:

... 
if (isCellSelected(index_row, index_col)){ 
    comp.setBackground(Color.GRAY); 
} else { 
    if (index_col == 34) { 
     comp.setBackground(Color.GRAY);     
    } else { 
     comp.setBackground(Color.WHITE); 
    } 
} 
... 
+0

100%。優秀。這讓我很煩惱了一段時間。謝謝。 – user237462 2014-10-02 10:44:33