Shade Rows and Columns in a JTable in Java
Description
The following code shows how to shade Rows and Columns in a JTable.
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
//from w w w . j a v a2 s . c o m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
{ "Row2-Column1", "Row2-Column2", "Row2-Column3" },
{ "Row3-Column1", "Row3-Column2", "Row3-Column3" }};
Object columnNames[] = { "Column One", "Column Two", "Column Three" };
final JTable table = new JTable(rowData, columnNames) {
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) {
Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
if (rowIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex)) {
c.setBackground(Color.yellow);
} else {
c.setBackground(getBackground());
}
return c;
}
};
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »