Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 <strong>prepareRenderer</strong>(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
Color <strong>alternateColor </strong>= new Color(200, 201, 210);
Color whiteColor = Color.WHITE;
if(!comp.getBackground().equals(getSelectionBackground())) {
Color c = (row % 2 == 0 ? <strong>alternateColor </strong>: <strong>whiteColor</strong>);
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
Advertisements
