How to Alternate Row Color of JTable in Java
In this tutorial, we are going to see how to alternate row color of a JTable in Java. JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected in a JTable, a TableModelEvent is generated, which is handled by implementing TableModelListener interface.
We can set the color to alternate the color of the rows in a JTable by redefining the method prepareRenderer() of JTable class.
Syntax:
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Java Program to Alternate Row Color of JTable
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class JtableColor extends JFrame { public JtableColor() { setTitle("Alternate JTable color"); //JTable Headers String[] columns = new String[]{"Id","Name","Address","Hourly rate"}; //data for JTable in a 2D table Object[][] data = new Object[][] { {1, "Thomas", "Alaska", 20.0 }, {2, "Jean", "Arizona", 50.0 }, {3, "Yohan", "California", 30.0 }, {4, "Emily", "Florida", 60.0 }, {5, "Alex", "New York", 10.0 }, }; JTable table = new JTable(data, columns) { public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); Color color1 = new Color(220,220,220); Color color2 = Color.WHITE; if(!c.getBackground().equals(getSelectionBackground())) { Color coleur = (row % 2 == 0 ? color1 : color2); c.setBackground(coleur); coleur = null; } return c; } }; add(new JScrollPane(table)); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JtableColor(); } }
Output: