1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.cosylab.gui.components.table.renderers;
21
22 import com.cosylab.gui.components.numberfield.DoubleDocument;
23 import com.cosylab.gui.components.table.cells.DoubleCell;
24
25 import com.cosylab.util.FormatCache;
26 import com.cosylab.util.PrintfFormat;
27 import com.cosylab.util.StringUtilities;
28
29 import java.awt.Component;
30
31 import java.text.DecimalFormat;
32
33 import java.util.EventObject;
34
35 import javax.swing.JTable;
36
37
38
39
40
41
42
43
44 public class DoubleCellEditor extends JTextFieldCellEditor
45 {
46 private static final long serialVersionUID = 1L;
47 private DoubleDocument document;
48 private boolean active;
49 private DecimalFormat f = new DecimalFormat("#.####################");
50
51
52
53
54 public DoubleCellEditor()
55 {
56 setDocument(document = new DoubleDocument());
57 }
58
59
60
61
62
63 public Component getTableCellEditorComponent(JTable table, Object cell,
64 boolean isSelected, int row, int column)
65 {
66 if (cell instanceof DoubleCell) {
67 active = !((DoubleCell)cell).isSuspended();
68
69 document.setMaxValue(((DoubleCell)cell).getMaximum());
70 document.setMinValue(((DoubleCell)cell).getMinimum());
71
72 double d = ((DoubleCell)cell).getDoubleValue();
73
74 if (d < 1e20 && d > 1e-20) {
75 if (active) {
76 setText(f.format(d));
77 } else {
78 setText("");
79 }
80 } else {
81 PrintfFormat formatter = FormatCache.getFormatter(((DoubleCell)cell)
82 .getFormat());
83
84 if (formatter == null) {
85 formatter = FormatCache.getDefaultFormatter();
86 }
87
88 if (active) {
89 setText(formatter.sprintf(d));
90 } else {
91 setText("");
92 }
93 }
94
95 selectAll();
96 }
97
98 return this;
99 }
100
101
102
103
104 public Object getCellEditorValue()
105 {
106 return document.getValue();
107 }
108
109
110
111
112 protected boolean isValueValid()
113 {
114 return StringUtilities.isTrueNumber(getText());
115 }
116
117
118
119
120 public boolean isCellEditable(EventObject anEvent)
121 {
122
123
124
125 return super.isCellEditable(anEvent);
126 }
127
128 public static void main(String[] args)
129 {
130 PrintfFormat formatter = FormatCache.getFormatter("%.f");
131
132 System.out.println(formatter.sprintf(1e-20));
133
134 DecimalFormat f = new DecimalFormat("#.####################");
135
136 System.out.println(f.format(1e20));
137 }
138 }
139
140