سلام
به این کد یه نگاه بندازید:
class ColorRenderer extends JLabel implements TableCellRenderer {
public ColorRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
setText(value.toString());
}
if (isSelected) {
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
} else {
setBackground(table.getBackground());
setForeground(table.getForeground());
if (row % 2 == 0) {
setBackground(java.awt.Color.GRAY);
}
}
return this;
}
}
public class TableRowColor extends JFrame {
public TableRowColor() {
JTable table = new JTable(new DefaultTableModel(new Object[][]{
{"1", "2", "3", "4"},
{"2", "3", "4", "5"},
{"3", "4", "5", "6"},
{"4", "5", "6", "7"}},
new Object[]{"A", "B", "C", "D"}));
ColorRenderer cr = new ColorRenderer();
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumn(table.getColumnName(i)).setCellRen derer(cr);
}
JScrollPane scroll = new JScrollPane(table);
this.setContentPane(scroll);
this.setBounds(100, 50, 300, 150);
}
public static void main(String arg[]) {
TableRowColor test = new TableRowColor();
test.setVisible(true);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
}
}