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