01: package tijmp.ui;
02:
03: import javax.swing.SwingConstants;
04: import javax.swing.table.DefaultTableCellRenderer;
05:
06: /** A renderer that turns memory sizes into readable strings.
07: */
08: public class ReadableSizeRenderer extends DefaultTableCellRenderer {
09: private static final String[] sizes = { "B", "kB", "MB", "GB",
10: "TB", "PB" };
11:
12: public ReadableSizeRenderer() {
13: setHorizontalAlignment(SwingConstants.RIGHT);
14: }
15:
16: public void setValue(Object value) {
17: setText(getNiceNumber(((Long) value).longValue()));
18: }
19:
20: private String getNiceNumber(long l) {
21: double d = l;
22: int p = 0;
23: boolean negative = false;
24: if (d < 0) {
25: d = -d;
26: negative = true;
27: }
28: while (d > 1024) {
29: p++;
30: d /= 1024;
31: }
32: if (p > 0)
33: return String.format("%s%.2f %s", (negative ? "-" : ""), d,
34: sizes[p]);
35: return String.format("%d %s", l, sizes[p]);
36: }
37: }
|