Back to Java
2026-05-146 min read

Zebra Striped Table (Java)

Learn Zebra Striped Table (Java) step by step with clear examples and exercises.

Why This Matters

In this comprehensive Java lesson, we will delve into the creation of an aesthetically pleasing Zebra Striped Table. By learning how to implement this technique, you can enhance the overall look and feel of your applications' user interfaces, making them more engaging and easier to read. A zebra striped table is particularly useful when displaying large amounts of data as it improves readability and reduces eye strain.

Benefits of Zebra Striped Tables

  • Improved readability: The alternating row colors make it easier for users to quickly scan through long lists of data.
  • Reduced eye strain: By providing a visual break between rows, zebra striped tables can help prevent eye fatigue when working with large datasets.
  • Enhanced user experience: A well-designed table improves the overall look and feel of your application, making it more appealing to users.

Prerequisites

To follow this lesson, you should have a solid understanding of Java programming concepts such as variables, loops, arrays, and JFrame (for creating graphical user interfaces). Familiarity with Swing components like JTable, JScrollPane, DefaultTableModel, and TableCellRenderer would be beneficial but is not strictly necessary.

Essential Concepts to Understand Before Starting

  • JTable: A Swing component used for displaying data in a table format.
  • DefaultTableModel: An implementation of the TableModel interface that provides a simple way to create and manipulate data within a JTable.
  • TableCellRenderer: An interface responsible for rendering (i.e., drawing) the cells of a JTable.

Core Concept

To create a Zebra Striped Table in Java, we will use the JTable component from the Swing library. We'll customize its appearance by overriding the getRowHeight() and prepareRenderer(TableCellRenderer, int, int) methods of the DefaultTableCellRenderer class. These methods allow us to set the row height and provide a custom renderer for each cell, respectively.

Creating a Custom JTable

First, let's create a simple JTable with some data:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class ZebraStripedTable {
private static final String[] columnNames = {"Column 1", "Column 2", "Column 3"};
private static final Object[][] data = {
{1, "Row 1 Col 2", true},
{2, "Row 2 Col 2", false},
{3, "Row 3 Col 2", true},
// Add more rows as needed
};

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}

private static void createAndShowGUI() {
JFrame frame = new JFrame("Zebra Striped Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);

// Set up the custom renderer for the table
table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());

// Set odd row height to make stripes more visible
table.setRowHeight(23);

JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

In the above code, we define some sample data and create a JTable using it. We also set up a custom renderer for the table by creating the CustomTableCellRenderer class.

Creating a Custom Table Cell Renderer

Now let's implement the CustomTableCellRenderer class:

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;

public class CustomTableCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

// Set the background color based on the row index (every other row will have a different color)
if ((row + 1) % 2 == 0) {
setBackground(new Color(242, 242, 242)); // Light Gray
setForeground(Color.BLACK); // Set the font color to black
} else {
setBackground(Color.WHITE); // White
setForeground(new Color(150, 150, 150)); // Set the font color to a light gray
}

return this;
}
}

In the getTableCellRendererComponent() method, we override the default behavior of the renderer and set the background color for each cell based on the row index. We also adjust the font color to improve readability.

Worked Example

Now that you have a basic understanding of how to create a Zebra Striped Table in Java, let's try implementing it with some real data:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class ZebraStripedTableExample {
private static final String[] columnNames = {"ID", "Name", "Age"};
private static final Object[][] data = {
{1, "Alice", 25},
{2, "Bob", 30},
{3, "Charlie", 28},
// Add more rows as needed
};

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}

private static void createAndShowGUI() {
JFrame frame = new JFrame("Zebra Striped Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);

// Set up the custom renderer for the table
table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());

// Set odd row height to make stripes more visible
table.setRowHeight(23);

JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

In this example, we create a simple JTable with some sample data and set up the custom renderer to display the table in a Zebra Striped fashion. We also adjust the row height to make the stripes more visible.

Common Mistakes

  1. Forgetting to override the getRowHeight() method: To make the alternating background colors visible, it's essential to override the getRowHeight() method and return an odd number for all rows. This will ensure that the cells have a slight padding, making the stripes more noticeable.
@Override
public int getRowHeight() {
return 23; // Use an odd number (e.g., 21, 23, or 25)
}
  1. Setting the background color incorrectly: Make sure to set the background color for every other row by checking the row index modulo 2.
  1. Not setting the DefaultTableCellRenderer as the default renderer for the table: Remember to call table.setDefaultRenderer(Object.class, new CustomTableCellRenderer()) to apply the custom renderer to the table.
  1. Failing to set an odd row height: Make sure to set an odd number for the row height in both the example provided and your own implementations.

Practice Questions

  1. Modify the example provided earlier to display additional data columns like "Gender" and "Email".
  2. Create a custom JTable that alternates between red and white stripes instead of gray.
  3. Add sorting functionality to the zebra striped table example.
  4. Implement a resizable JFrame for the Zebra Striped Table Example.
  5. Modify the CustomTableCellRenderer to support different color schemes (e.g., black and white, blue and yellow).
  6. Create a custom TableCellEditor that allows users to edit cell values in the zebra striped table.
  7. Implement a search functionality for the zebra striped table.
  8. Add the ability to add, delete, and update rows in the zebra striped table.

FAQ

Q: Why are my stripes not visible?

A: Make sure you've overridden both getRowHeight() and prepareRenderer(TableCellRenderer, int, int) methods in your custom renderer class, and returned an odd number for the row height. Also, ensure that you've set the DefaultTableCellRenderer as the default renderer for the table.

Q: Why is my font color not readable on the light gray stripes?

A: Adjust the font color in the getTableCellRendererComponent() method to improve contrast with the light gray background.

Q: Can I use a different color scheme for the zebra striped table?

A: Yes, you can customize the colors by setting them as needed in the getTableCellRendererComponent() method or by creating multiple renderers for different color schemes.

Q: How do I add sorting functionality to my Zebra Striped Table?### Q: Can I customize the padding between cells in my Zebra Striped Table?

A: Yes, you can adjust the cell padding by setting the table.setIntercellSpacing(new Dimension(left, top, right, bottom)); method before adding the table to the JScrollPane.

Q: How do I handle different row heights for different columns in my Zebra Striped Table?

A: To handle different row heights for different columns, you can override the getPreferredSize(javax.swing.table.TableCellRenderer, Object, boolean, int, int) method in your custom renderer class and return a Dimension with the desired height based on the column index.

Q: How do I make my Zebra Striped Table scrollable both horizontally and vertically?

A: To make your table scrollable both horizontally and vertically, create a JScrollPane that wraps a JViewport containing your JTable. Set the horizontal and vertical scrollbars for the JScrollPane using setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS) and setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS).

Q: How do I add a border around my Zebra Striped Table?

A: To add a border around your table, create a Border object and set it as the border for the JTable using table.setBorder(border);. You can find various pre-built borders in Java, or you can create custom borders by implementing the Border interface.

Zebra Striped Table (Java) | Java | XQA Learn