2014-10-02 39 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