
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Change Background Color of JTable Rows in Java
In this program, we will create a JTable and change the background color of its rows. A JTable is used to display data in a tabular format, and by adjusting its properties, we can modify its appearance. The goal of this program is to set a custom background color for the rows of a JTable and change the font and row height to improve readability.
Steps to change the background color of rows in a JTable
Following are the steps to change the background color of rows in a JTable ?
- First, we will import the necessary classes and create a data model by defining a 2D array for the table data and a 1D array for column headers.
- Create a JTable by instantiating the JTable object using the data and column arrays.
- Set the font and row height using setFont() and setRowHeight() methods to adjust the table's appearance.
- After that, we will change the background colors using the setBackground() method to set the background color of the table rows.
- Display the table by adding the table to a JFrame using a JScrollPane for scrollable content, then set the frame's size and visibility.
Java program to change the background color of rows in a JTable
The following is an example of changing the background color of rows ?
package my; import java.awt.Color; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; public class SwingDemo { public static void main(String[] argv) throws Exception { Integer[][] marks = { { 70, 66, 76, 89, 67, 98 }, { 67, 89, 64, 78, 59, 78 }, { 68, 87, 71, 65, 87, 86 }, { 80, 56, 89, 98, 59, 56 }, { 75, 95, 90, 73, 57, 79 }, { 69, 49, 56, 78, 76, 77 } }; String col[] = { "S1", "S2", "S3", "S4", "S5", "S6"}; JTable table = new JTable(marks, col); Font font = new Font("Verdana", Font.PLAIN, 12); table.setFont(font); table.setRowHeight(30); table.setBackground(Color.blue); table.setForeground(Color.white); JFrame frame = new JFrame(); frame.setSize(600, 400); frame.add(new JScrollPane(table)); frame.setVisible(true); } }
Output
Code explanation
The program creates a JTable using predefined data (marks) and column names (col). The setBackground(Color.blue) method changes the background color of all rows to blue. Additionally, the text color is set to white using setForeground(Color.white). The font and row height are modified for better readability. Finally, the table is displayed in a scrollable window (JScrollPane) inside a JFrame.