/ / JTableの特定のセルの色の変更-java、swing、colors、jtable、cell

JTable内の特定のセルの色を変更する - Java、スイング、カラー、jtable、セル

JTableの列にある1つ以上の特定のセルの色を変更しようとしています。ここで見た答えはすべて、この特定のメソッドを参照しています。

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component y = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
y.setBackground(new Color(255,0,0));

return y;
}

しかし、問題は私が決して理解していないことですこれがどのように機能するか、他のクラスには文字列のJtableがあり、文字列値に応じて特定のセルの色を変更したいのですが、私が見つける解決策では、セルの列全体の色を変更することしかできませんjtableであり、特定のものではありません。

回答:

回答№1は5

文字列のJtableがあり、文字列値に応じて特定のセルの色を変更したい

同じレンダラーがすべてのセルに使用されるため、毎回背景をリセットする必要があります。

カスタムレンダラーコードにはif条件が必要です。何かのようなもの:

if (!isSelected)
if (value.equals(...))
y.setBackground(new Color(255,0,0));
else
y.setBackground(table.getBackground())

回答№2の場合は0

DefaultTableCellRendererを使用して、JTableの代替行に色を付けることができます。

table.setDefaultRenderer(Object.class, new TableCellRenderer(){
private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected){
c.setBackground(Color.YELLOW);
}else{
if (row%2 == 0){
c.setBackground(Color.WHITE);

}
else {
c.setBackground(Color.LIGHT_GRAY);
}     }

//Add below code here
return c;
}

});

特定の行の値を使用して行を色付けする場合は、次のようなものを使用できます。上記にこれらの行を追加します

if(table.getColumnModel().getColumn(column).getIdentifier().equals("Status")){//Here `Status` is column name
if(value.toString().equals("OK")){//Here `OK` is the value of row

c.setBackground(Color.GREEN);
}
}