برای تغییر رنگ سلول های jtable توی جاوا راه های مختلفی هست ولی ساده ترین روشی که من پیدا کردم اینه
اول از همه این 2 تا رو فراخوانی می کینید
import java.awt.Component;
import javax.swing.table.TableCellRenderer;
بعد روی تیبل راست کلیک میکنید و گزینه customize code رو انخاب میکنید
توی خط اول گزینه زیر رو میبینید ( فرض بر اینه نام jtable رو تغییر ندادیدن اگه عوضش کرده باشین اسمش میشه اسمی که شما براش انتخاب کردین )
jTable1 = new javax.swing.JTable();
کنارش یه کومبو باکس میبینید که مقدار پیش فرضش default code هستش اون رو به custom creation تغییر بدین :
قبل از سیم کالن ; آخر خط چند تا اینتر بزنید و کدهای زیر رو اونجا بنویسید:( کد های زیر اگه روی سطری کلیک کنید سبز میشه و سلولی خالی باشه یا کلمه null توش نوشته شده باشه رنگ اون سلول های خاص رو عوض میکنه شما نسبت به شرایطی که دارید میتونید شرط ها رو تغییر بدین )
{
public Component prepareRenderer ( TableCellRenderer renderer, int row, int column ){
Component component = super.prepareRenderer(renderer,row,column);
if (getModel().getValueAt(row,column) == null){
component.setBackground(Color.ORANGE);
}
else if (getModel().getValueAt(row,column) != null){
Object value = getModel().getValueAt(row,column);
if (isRowSelected(row))
{
component.setBackground(Color.GREEN);
component.setForeground(Color.BLACK);
}
else if(value.equals("null")){
component.setBackground(Color.RED);
component.setForeground(Color.BLACK);
}
else if(value.equals("")){
component.setBackground(Color.BLUE);
component.setForeground(Color.BLACK);
}
else{
component.setBackground(Color.WHITE);
component.setForeground(Color.BLACK);
}
}
return component;
}
}
نهایتا کدتون مثل این باید بشه:
jTable1 = new javax.swing.JTable()
{
public Component prepareRenderer ( TableCellRenderer renderer, int row, int column ){
Component component = super.prepareRenderer(renderer,row,column);
if (getModel().getValueAt(row,column) == null){
component.setBackground(Color.ORANGE);
}
else if (getModel().getValueAt(row,column) != null){
Object value = getModel().getValueAt(row,column);
if (isRowSelected(row))
{
component.setBackground(Color.GREEN);
component.setForeground(Color.BLACK);
}
else if(value.equals("null")){
component.setBackground(Color.RED);
component.setForeground(Color.BLACK);
}
else if(value.equals("")){
component.setBackground(Color.BLUE);
component.setForeground(Color.BLACK);
}
else{
component.setBackground(Color.WHITE);
component.setForeground(Color.BLACK);
}
}
return component;
}
}
;
در ضمن اگر خواستین یک در میون سطر هاتون رنگی باشه قبل از سلکت کردن یه سطر کافیه به جای
else{
component.setBackground(Color.WHITE);
component.setForeground(Color.BLACK);
}
از کد زیر استفاده کنید
else{
if (row%2 == 0){
component.setBackground(new Color(255, 255, 253));
component.setForeground(Color.BLACK);
}
else {
component.setBackground(new Color(208,205,205));
component.setForeground(Color.BLACK);
}
}