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.table;
21
22 import java.awt.Color;
23 import java.awt.FontMetrics;
24 import java.awt.Graphics;
25 import javax.swing.table.DefaultTableCellRenderer;
26 import org.xnap.commons.i18n.I18n;
27 import org.xnap.commons.i18n.I18nFactory;
28 import org.xnap.commons.util.Progress;
29 import org.xnap.commons.util.StringHelper;
30
31 /***
32 * Renders progress in a progress bar with a text for a table cell.
33 *
34 * @see Progress
35 */
36 public class ProgressCellRenderer extends DefaultTableCellRenderer {
37
38 private static final I18n i18n = I18nFactory.getI18n(ProgressCellRenderer.class);
39
40 private static Color runningColor = Color.magenta;
41 private static Color finishedColor = Color.green;
42
43 private Progress value = new Progress();
44 private String text;
45
46 public ProgressCellRenderer()
47 {
48 }
49
50 protected void setValue(Object value)
51 {
52 this.value
53 = (value instanceof Progress)
54 ? (Progress)value
55 : new Progress();
56
57 this.text = getProgressText();
58 setToolTipText(String.format("%f.2", this.value.getPercent())
59 + "%" + ((text.length() == 0) ? "" : ", " + text));
60
61 super.setValue(null);
62 }
63
64 public String getProgressText()
65 {
66 long rate = value.getRate();
67 if (rate < 0) {
68 return "";
69 }
70 else if (rate == 0) {
71 return i18n.tr("stalled");
72 }
73 else {
74 return i18n.tr(StringHelper.formatSize(rate) + "/s");
75 }
76 }
77
78 public void paint(Graphics g)
79 {
80 super.paint(g);
81
82 double progress = value.getPercent();
83
84 int xoff = 1;
85 int yoff = 1;
86 int height = getHeight() - 3;
87 int width = getWidth() - 2;
88
89
90 if (progress > 0) {
91 g.setColor((progress < 100) ? runningColor : finishedColor);
92 g.fillRect(xoff, yoff, (width * (int)progress) / 100, height);
93 }
94
95
96 if (text != null && text.length() > 0) {
97 FontMetrics fm = g.getFontMetrics();
98 int w = fm.stringWidth(text);
99
100 int x = (getWidth() - w) / 2;
101 int y = getHeight() - 4;
102
103 g.setColor(getForeground());
104 g.drawString(text, (x > 1) ? x : 1, y);
105 }
106
107
108 g.setColor(Color.lightGray);
109 g.drawRect(1, 1, getWidth() - 2, getHeight() - 3);
110 }
111
112 }