Java jtable simple renderer example

Here's an example of how to use a simple cell renderer for a JTable in Java:

import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class TableSimpleRendererExample extends JFrame {

    public TableSimpleRendererExample() {
        super("Table Simple Renderer Example");

        // Create the table
        Object[][] data = {
                {"John Doe", "25", "Male"},
                {"Jane Smith", "30", "Female"},
                {"Bob Johnson", "40", "Male"}
        };
        String[] columnNames = {"Name", "Age", "Gender"};
        JTable table = new JTable(data, columnNames);

        // Create the cell renderer
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                c.setBackground(row % 2 == 0 ? getBackground() : java.awt.Color.LIGHT_GRAY);
                return c;
            }
        };

        // Set the cell renderer for the second column
        table.getColumnModel().getColumn(1).setCellRenderer(renderer);

        // Add the table to a scroll pane
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        // Set the size, location and visibility of the frame
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TableSimpleRendererExample();
    }
}
Source:‮gi.www‬iftidea.com

In this example, we create a JTable and add it to a JScrollPane. We then create a custom cell renderer by extending the DefaultTableCellRenderer class and overriding its getTableCellRendererComponent method. In this method, we call the super method to get the default rendering of the cell, and then we set the background color of the cell to either the default color or light gray, depending on whether the row is even or odd.

We then set this custom renderer for the second column of the JTable by calling the setCellRenderer method on the TableColumnModel of the table. This will apply the custom renderer to all cells in the second column.

When you run this example, the second column of the JTable will have alternating background colors, with one row having a light gray background and the next row having the default background color.