You want to paint the Row of your JTable.
Create a new class that inherits from DefaultTableCellRenderer to handle the render of your cells.
package ejemplo;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class RowsRenderer extends DefaultTableCellRenderer {
private int columna ;
public RowsRenderer(int Colpatron)
{
this.columna = Colpatron;
}
@Override
public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column)
{
setBackground(Color.white);
table.setForeground(Color.black);
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
if(table.getValueAt(row,columna).equals("A"))
{
this.setForeground(Color.RED);
}else if(table.getValueAt(row,columna).equals("B")){
this.setForeground(Color.BLUE);
}else if(table.getValueAt(row, columna).equals("C")){
this.setForeground(Color.GREEN);
}
return this;
}
}
Class main of the example:
package ejemplo;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JPanelDemo extends JFrame {
private String columnas[] = {"Auto", "Color", "Tipo"};
private Object celdas[][] = {{"Kia","Rojo", "C"},
{"Toyota","Azul","C"},
{"Lexus","Negro","B"},
{"BMW","Verde","B"},
{"Pagani", "Dorado", "A"},
{"Ferrari", "Rojo", "A"}
};
private JTable tabla;
public JPanelDemo(){
super("JTable Color");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
tabla = new JTable(celdas,columnas);
RowsRenderer rr = new RowsRenderer(2);
tabla.setDefaultRenderer(Object.class, rr);
add(new JScrollPane(tabla));
setVisible(true);
pack();
}
public static void main(String[]args){
JPanelDemo obj = new JPanelDemo();
}
}
- If the car is type C, then the row text will be painted in
Green.
- If the car is type B, then the text in the row will be painted Blue.
- If the car is type A, then the text in the row will be painted in Red.