

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set the color to alternate rows of JTable in Java?
A 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 from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface.
We can set the color to alternate rows of JTable by overriding the prepareRenderer() method of JTable class.
Syntax
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class AlternateRowColorTableTest extends JFrame { public AlternateRowColorTableTest() { setTitle("AlternateRowColorTable Test"); JTable table = new JTable(new Object[][] {{"115", "Ramesh"}, {"120", "Adithya"}, {"125", "Jai"}, {"130", "Chaitanya"}, {"135", "Raja"}}, new String[] {"Employee Id", "Employee Name"}) { public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component comp = super.prepareRenderer(renderer, row, column); Color alternateColor = new Color(200, 201, 210); Color whiteColor = Color.WHITE; if(!comp.getBackground().equals(getSelectionBackground())) { Color c = (row % 2 == 0 ? alternateColor : whiteColor); comp.setBackground(bg); c = null; } return returnComp; } }; add(new JScrollPane(table)); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new AlternateRowColorTableTest(); } }
Output
- Related Questions & Answers
- Java Program to change the background color of rows in a JTable
- Java Program to set different height for multiple rows in JTable
- How can we set the background/foreground color for individual column of a JTable in Java?
- Java Program to set the height of only a single row in a JTable with multiple rows
- How to get the number of rows and columns of a JTable in Java Swing
- How to set magins between cells of a JTable in Java?
- How to set the grid color of a table in Java?
- How to set multidimensional array into JTable with Java?
- How to set color to MatteBorder in Java?
- How to set a value in a particular JTable cell with Java?
- How to set border color for SoftBevelBorder in Java?
- How to implement the search functionality of a JTable in Java?
- How can we set the background color to a JPanel in Java?
- How to set the color of a text with CSS
- How to set the border color of certain Tkinter widgets?
Advertisements