JTable - 为什么单元格颜色不起作用
JTable - Why cell color doesn't work
我有 4 列的 JTable。我只想根据每个单元格的值呈现索引 2 的列(即 'Change' 列)。
看看我的代码
private DefaultTableModel tmodel;
private final int table_colID_at_compID = 0;
private final int table_colID_at_compName = 1;
private final int table_colID_at_stockPresentageGrowth = 2;
private final int table_colID_at_compNetWorth = 3;
..........more code(unimportant code)..........
tmodel = new DefaultTableModel( new String[][] {} ,new String[]{"Comp. ID","Com. Name","Change %","Net Worth"} );
table = new JTable(tmodel){
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex, int columnIndex){
Component componenet = super.prepareRenderer(renderer, rowIndex, columnIndex);
if(columnIndex == table_colID_at_stockPresentageGrowth) {
double value = new Double(getValueAt(rowIndex, columnIndex).toString());
if( value < 0 )
componenet.setBackground(Color.RED);
else if( value == 0)
componenet.setBackground(Color.WHITE);
else
componenet.setBackground(Color.GREEN);
}
return componenet;
}
};
- 名称为
table_colID_at_<something>
的所有变量代表 table 列 ID。
- 如下图所示,程序绘制了 2 列('Change' 和 'Net worth'。)(它应该只绘制 'Change' 列)
- 我调试了程序,发现if语句没问题。
- 所以我认为问题出在操作背后的逻辑上。
图片:(imgur有错误)
对于每隔一列,您必须将颜色设置回白色。
我有 4 列的 JTable。我只想根据每个单元格的值呈现索引 2 的列(即 'Change' 列)。 看看我的代码
private DefaultTableModel tmodel;
private final int table_colID_at_compID = 0;
private final int table_colID_at_compName = 1;
private final int table_colID_at_stockPresentageGrowth = 2;
private final int table_colID_at_compNetWorth = 3;
..........more code(unimportant code)..........
tmodel = new DefaultTableModel( new String[][] {} ,new String[]{"Comp. ID","Com. Name","Change %","Net Worth"} );
table = new JTable(tmodel){
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex, int columnIndex){
Component componenet = super.prepareRenderer(renderer, rowIndex, columnIndex);
if(columnIndex == table_colID_at_stockPresentageGrowth) {
double value = new Double(getValueAt(rowIndex, columnIndex).toString());
if( value < 0 )
componenet.setBackground(Color.RED);
else if( value == 0)
componenet.setBackground(Color.WHITE);
else
componenet.setBackground(Color.GREEN);
}
return componenet;
}
};
- 名称为
table_colID_at_<something>
的所有变量代表 table 列 ID。 - 如下图所示,程序绘制了 2 列('Change' 和 'Net worth'。)(它应该只绘制 'Change' 列)
- 我调试了程序,发现if语句没问题。
- 所以我认为问题出在操作背后的逻辑上。
图片:(imgur有错误)
对于每隔一列,您必须将颜色设置回白色。