1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.gui;
21
22 import java.awt.Color;
23 import java.awt.Component;
24 import javax.swing.JTable;
25 import javax.swing.UIManager;
26 import javax.swing.table.TableCellRenderer;
27 import javax.swing.table.TableColumnModel;
28 import javax.swing.table.TableModel;
29
30 /***
31 * A table that uses a different background color for every other row in the
32 * table.
33 * TODO provide setter for colors
34 * TODO lighten other color for dark themes
35 */
36 public class ColoredTable extends JTable
37 {
38
39 private Color oddColor;
40 private Color evenColor;
41
42 public ColoredTable(TableModel dm, TableColumnModel cm)
43 {
44 super(dm, cm);
45 updateColors();
46 }
47
48 public ColoredTable(TableModel dm)
49 {
50 super(dm);
51 updateColors();
52 }
53
54 public ColoredTable()
55 {
56 updateColors();
57 }
58
59 public Color getBackgroundColor(int row)
60 {
61 return (row % 2 == 1) ? oddColor : evenColor;
62 }
63
64 private void updateColors()
65 {
66 evenColor = UIManager.getColor("Table.background");
67
68 oddColor = (evenColor != null)
69 ? new Color(Math.max((int)(evenColor.getRed() * 0.9), 0),
70 Math.max((int)(evenColor.getGreen() * 0.9), 0),
71 Math.max((int)(evenColor.getBlue() * 0.9), 0))
72 : null;
73 }
74
75 public void updateUI()
76 {
77 super.updateUI();
78 updateColors();
79 }
80
81 /***
82 * The idea for this implementation stems from LimeWire's
83 * JMultilineToolTipTreeTable, thanks guys.
84 */
85 @Override
86 public Component prepareRenderer(TableCellRenderer renderer, int row,
87 int column)
88 {
89 Component c = super.prepareRenderer(renderer, row, column);
90
91 boolean isSelected = isCellSelected(row, column);
92 boolean rowIsAnchor =
93 (selectionModel.getAnchorSelectionIndex() == row);
94 boolean colIsAnchor =
95 (columnModel.getSelectionModel().getAnchorSelectionIndex()
96 == column);
97 boolean hasFocus = (rowIsAnchor && colIsAnchor) && hasFocus();
98 if (!isSelected && !hasFocus) {
99 c.setBackground(getBackgroundColor(row));
100 }
101 return c;
102 }
103
104 }