根据JTable中的第一列值着色特定行? [英] Coloring particular rows according to the first column values in JTable?
问题描述
我正在尝试根据 JTable
中的第一列值为特定行着色,但下面的代码根据行的索引为行着色。我的表只有四列。第一列有ID号。我需要根据这些ID号对行进行着色。例如,如果第一个ID为0而第二个ID也为0,则它们都应为lightGray。请问有什么想法吗?
table_1 = new JTable(){
public Component prepareRenderer(TableCellRenderer renderer,int Index_row, int Index_col){
Component comp = super.prepareRenderer(renderer,Index_row,Index_col);
//偶数索引,选中或未选中
if(Index_row%2 == 0&&!isCellSelected(Index_row,Index_col)){
comp.setBackground(Color.lightGray) ;
} else {
comp.setBackground(Color.white);
}
返回comp;
}
};
以下是现在的样子:
您的渲染器根据传递给 prepareRenderer()
的行
参数选择颜色。谓词行%2 == 0
选择交替行进行着色,如图所示。您的问题意味着您实际上希望以第0列的值为基础着色, ID
。为此你需要检查 getValueAt(row,0)
的结果。
确切的表述取决于你的模特。使用此所述。
I'm trying to color particular rows according to the first column values in JTable
, but the code below colors the rows according to the row's index. My table has simply four columns. The first column has ID numbers. I need to color the rows according to these ID numbers. For example, if the first ID is 0 and the second is also 0, both of them should be "lightGray". Any idea, please?
table_1 = new JTable(){
public Component prepareRenderer(TableCellRenderer renderer,int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer,Index_row, Index_col);
//even index, selected or not selected
if (Index_row % 2==0 && !isCellSelected(Index_row, Index_col)) {
comp.setBackground(Color.lightGray);
} else {
comp.setBackground(Color.white);
}
return comp;
}
};
Here is how it looks now:
Your renderer is choosing the color based on the row
parameter passed to prepareRenderer()
. The predicate row % 2 == 0
selects alternating rows for shading, as shown in your picture. Your question implies that you actually want to base shading on the value of column zero, ID
. For this you need to examine the result of the getValueAt(row, 0)
.
The exact formulation depends on your model. Using this example, the following renderer shades rows starting with the letter "T".
private JTable table = new JTable(dataModel) {
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
int modelRow = convertRowIndexToModel(row);
if (((String) dataModel.getValueAt(modelRow, 0)).startsWith("T")
&& !isCellSelected(row, col)) {
comp.setBackground(Color.lightGray);
} else {
comp.setBackground(Color.white);
}
return comp;
}
};
Addendum: @mKorbel helpfully comments on the need to convert between model and view coordinates when sorting is enabled, as discussed here.
这篇关于根据JTable中的第一列值着色特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!