Statistics
| Revision:

gvsig-tools / org.gvsig.tools / library / trunk / org.gvsig.tools / org.gvsig.tools.dynform / org.gvsig.tools.dynform.spi / src / main / java / org / gvsig / tools / dynform / spi / dynformfield / AbstractJDynFormFieldWithValueList.java @ 2487

History | View | Annotate | Download (14.8 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.tools.dynform.spi.dynformfield;
25

    
26
import java.awt.event.FocusListener;
27
import java.awt.event.ItemEvent;
28
import java.awt.event.KeyAdapter;
29
import java.awt.event.KeyEvent;
30
import java.util.Objects;
31
import javax.swing.BorderFactory;
32
import javax.swing.ComboBoxModel;
33
import javax.swing.DefaultComboBoxModel;
34

    
35
import javax.swing.JComboBox;
36
import javax.swing.JLabel;
37
import javax.swing.JSpinner;
38
import javax.swing.JTextField;
39
import javax.swing.UIManager;
40
import javax.swing.event.ChangeEvent;
41
import javax.swing.event.DocumentEvent;
42
import javax.swing.event.DocumentListener;
43
import javax.swing.text.JTextComponent;
44
import org.apache.commons.lang3.StringUtils;
45

    
46
import org.gvsig.tools.dataTypes.CoercionException;
47
import org.gvsig.tools.dynform.DynFormFieldDefinition;
48
import org.gvsig.tools.dynform.JDynFormField;
49
import org.gvsig.tools.dynform.spi.DynFormSPIManager;
50
import org.gvsig.tools.dynform.spi.DynFormSPIManager.ComponentsFactory;
51
import static org.gvsig.tools.dynform.spi.DynFormSPIManager.TAG_DYNFORM_DROPDOWN;
52
import org.gvsig.tools.dynform.spi.dynformfield.AbstractJDynFormField.IllegalFieldValue;
53
import org.gvsig.tools.dynobject.DynObjectValueItem;
54
import org.gvsig.tools.dynobject.exception.DynFieldValidateException;
55
import org.gvsig.tools.swing.api.DropDown;
56
import org.gvsig.tools.swing.api.ToolsSwingLocator;
57

    
58
public abstract class AbstractJDynFormFieldWithValueList extends AbstractJDynFormField implements JDynFormField, FocusListener {
59

    
60
    protected Object assignedValue = null;
61
    protected DropDown dropDown = null;
62

    
63
    public AbstractJDynFormFieldWithValueList(
64
            DynFormSPIManager serviceManager,
65
            ComponentsFactory componentsFactory,
66
            JDynFormFieldFactory factory,
67
            DynFormFieldDefinition definition,
68
            Object value
69
    ) {
70
        super(serviceManager, componentsFactory, factory, definition, value);
71
        this.assignedValue = value;
72
    }
73

    
74
    @Override
75
    public Object getAssignedValue() {
76
        return this.assignedValue;
77
    }
78

    
79
    protected JTextField getJTextField() {
80
        if (this.contents instanceof JTextField) {
81
            return (JTextField) this.contents;
82
        }
83
        return null;
84
    }
85

    
86
    protected JSpinner getJSpinnerField() {
87
        if (this.contents instanceof JSpinner) {
88
            return (JSpinner) this.contents;
89
        }
90
        return null;
91
    }
92

    
93
    protected DropDown getDropDown() {
94
        return this.dropDown;
95
    }
96

    
97
    protected DynObjectValueItem[] getAvailableValues() {
98
        return this.getDefinition().getAvailableValues();
99
    }
100

    
101
    @Override
102
    public void initComponent() {
103
        DynObjectValueItem[] availableValues = this.getAvailableValues();
104
        ComponentsFactory theFactory = this.getComponentsFactory();
105
        if (theFactory.containsJComboBox(this.getDefinition(), null)) {
106
            JComboBox combo = this.getComponentsFactory().getJComboBox(this.getDefinition(), null);
107
            this.dropDown = ToolsSwingLocator.getToolsSwingManager().createDropDown(combo);
108
            this.dropDown.setModel(new DefaultComboBoxModel(availableValues));
109
            this.contents = combo;
110
            this.dropDown.addItemListener((ItemEvent e) -> {
111
                if (e.getStateChange() == ItemEvent.SELECTED) {
112
                    fireFieldChangedEvent();
113
                }
114
            });
115

    
116
        } else if (theFactory.containsJLabel(this.getDefinition(), "Ddn")) {
117
            JLabel label = this.getComponentsFactory().getJLabel(this.getDefinition(), "Ddn");
118
            this.dropDown = ToolsSwingLocator.getToolsSwingManager().createDropDown(label);
119
            this.dropDown.setModel(new DefaultComboBoxModel(availableValues));
120
            this.dropDown.setVisibleDropdownArrow(true);
121
            this.contents = label;
122
            this.dropDown.addItemListener((ItemEvent e) -> {
123
                if (e.getStateChange() == ItemEvent.SELECTED) {
124
                    fireFieldChangedEvent();
125
                }
126
            });
127

    
128
        } else if (theFactory.containsJSpinner(this.getDefinition(), null)) {
129
            JSpinner spinner = this.getComponentsFactory().getJSpinner(this.getDefinition(), null);
130
            this.contents = spinner;
131
            this.dropDown = null;
132
            spinner.addChangeListener((ChangeEvent e) -> {
133
                fireFieldChangedEvent();
134
            });
135

    
136
        } else if (theFactory.containsJTextField(this.getDefinition(), null)) {
137
            JTextComponent text = theFactory.getJTextField(this.getDefinition(), null);
138
            this.contents = text;
139
            this.dropDown = null;
140
            text.getDocument().addDocumentListener(new DocumentListener() {
141
                @Override
142
                public void insertUpdate(DocumentEvent e) {
143
                    fireFieldChangedEvent();
144
                }
145

    
146
                @Override
147
                public void removeUpdate(DocumentEvent e) {
148
                    fireFieldChangedEvent();
149
                }
150

    
151
                @Override
152
                public void changedUpdate(DocumentEvent e) {
153
                    fireFieldChangedEvent();
154
                }
155
            });
156
        } else {
157
            if (availableValues == null) {
158
                this.dropDown = null;
159
                JTextComponent text = this.getComponentsFactory().getJTextField(this.getDefinition(), null);
160
                this.contents = text;
161
                text.getDocument().addDocumentListener(new DocumentListener() {
162
                    @Override
163
                    public void insertUpdate(DocumentEvent e) {
164
                        fireFieldChangedEvent();
165
                    }
166

    
167
                    @Override
168
                    public void removeUpdate(DocumentEvent e) {
169
                        fireFieldChangedEvent();
170
                    }
171

    
172
                    @Override
173
                    public void changedUpdate(DocumentEvent e) {
174
                        fireFieldChangedEvent();
175
                    }
176
                });
177
            } else {
178
                String dropdownType = this.getTagValueAsString(TAG_DYNFORM_DROPDOWN,
179
                        availableValues.length <= 20 ? "label" : "combo"
180
                ).toLowerCase().trim();
181
                switch (dropdownType) {
182
                    case "label": {
183
                        JLabel label = this.getComponentsFactory().getJLabel(this.getDefinition(), "Ddn");
184
                        this.dropDown = ToolsSwingLocator.getToolsSwingManager().createDropDown(label);
185
                        this.dropDown.setModel(new DefaultComboBoxModel(availableValues));
186
                        this.dropDown.setVisibleDropdownArrow(true);
187
                        label.setBorder(BorderFactory.createLineBorder(UIManager.getColor("TextField.darkShadow")));
188
                        label.setForeground(UIManager.getColor("TextField.foreground"));
189
                        label.setBackground(UIManager.getColor("TextField.background"));
190
                        label.setOpaque(true);
191
                        this.contents = label;
192
                        break;
193
                    }
194
                    default:
195
                    case "combo": {
196
                        JComboBox combo = this.getComponentsFactory().getJComboBox(this.getDefinition(), null);
197
                        this.dropDown = ToolsSwingLocator.getToolsSwingManager().createDropDown(combo);
198
                        this.dropDown.setModel(new DefaultComboBoxModel(availableValues));
199
                        this.contents = combo;
200
                        break;
201
                    }
202
                }
203
                this.dropDown.addItemListener((ItemEvent e) -> {
204
                    if (e.getStateChange() == ItemEvent.SELECTED) {
205
                        fireFieldChangedEvent();
206
                    }
207
                });
208
            }
209
        }
210
        this.contents.addFocusListener(this);
211
        this.setReadOnly(readOnly); // Forzamos a actualiza rel estado del component
212
        //component dont have support to set null values
213
        if (theFactory.containsJSpinner(this.getDefinition(), null) && this.assignedValue == null) {
214
            this.setValue(0);
215
        } else {
216
            this.setValue(this.assignedValue);
217
        }
218
    }
219

    
220
    @Override
221
    public void setReadOnly(boolean readonly) {
222
        if (!readonly && this.isForcedReadOnly()) {
223
            readonly = true;
224
        }
225
        if (this.dropDown == null) {
226
            super.setReadOnly(readonly);
227
        } else {
228
            this.readOnly = readonly;
229
            if (jlabel != null) {
230
                this.jlabel.setEnabled(!readonly);
231
            }
232
            this.dropDown.setReadOnly(readonly);
233
        }
234
    }
235

    
236
    protected String getValueFromJComponent() {
237
        String s;
238
        if (this.dropDown == null) {
239
            JTextField jtext = this.getJTextField();
240
            if (jtext == null) {
241
                s = null;
242
            } else {
243
                s = jtext.getText();
244
            }
245
        } else {
246
            DynObjectValueItem value = (DynObjectValueItem) this.dropDown.getSelectedItem();
247
            if (value == null) {
248
                s = null;
249
            } else {
250
                s = Objects.toString(value.getValue(), null);
251
            }
252
        }
253
        if (StringUtils.isBlank(s) && this.translateEmptyToNull()) {
254
            return null;
255
        }
256
        return s;
257
    }
258

    
259
    @Override
260
    public void setValue(Object value) {
261
        if (this.dropDown == null) {
262
            JTextField jtext = this.getJTextField();
263
            if (jtext != null) {
264
                this.setTranslateEmptyToNull(value == null);
265
//                String s;
266
//                if (value == null) {
267
//                    this.setTranslateEmptyToNull(true);
268
//                    value = this.getDefinition().getDefaultValue();
269
//                    if (value == null) {
270
//                        s = this.getDefaultValue();
271
//                    } else {
272
//                        s = value.toString();
273
//                    }
274
//                } else {
275
//                    this.setTranslateEmptyToNull(false);
276
//                    s = value.toString();
277
//                    try {
278
//                        this.getDefinition().validate(value);
279
//                        this.problemIndicator().clear();
280
//                    } catch (DynFieldValidateException e) {
281
//                        this.problemIndicator().set(e.getLocalizedMessage());
282
//                    }
283
//                }
284
                jtext.setText(Objects.toString(value, ""));
285
            } else if (this.contents instanceof JSpinner) {
286
                JSpinner jspinner = this.getJSpinnerField();
287
                if (value == null) {
288
                    //FIXME: Como poner un nulo a un JSpinner
289
                    this.setTranslateEmptyToNull(true);
290
                    value = this.getDefinition().getDefaultValue();
291
                    if (value != null) {
292
                        jspinner.setValue(value);
293
                    } else {
294
                        jspinner.setValue(121);
295
                    }
296
                } else {
297
                    this.setTranslateEmptyToNull(false);
298
                }
299
                jspinner.setValue(value);
300
            }
301
        } else {
302
            if (value == null) {
303
                this.dropDown.setSelectedIndex(-1);
304
            } else {
305
                ComboBoxModel model = this.dropDown.getModel();
306
                if (model != null) {
307
                    for (int i = 0; i < model.getSize(); i++) {
308
                        DynObjectValueItem item = (DynObjectValueItem) model.getElementAt(i);
309
                        if (item != null && Objects.equals(item.getValue(), value)) {
310
                            this.dropDown.setSelectedIndex(i);
311
                            break;
312
                        }
313
                    }
314
                }
315
            }
316
        }
317
        this.assignedValue = value;
318
    }
319

    
320
    /* 
321
         * M?todos espec?ficos de cada tipo de datos
322
     */
323
    protected String getDefaultValue() {
324
        return "";
325
    }
326

    
327
    @Override
328
    public Object getValue() {
329
        Object value = null;
330
        String s = this.getValueFromJComponent();
331
        try {
332
            value = this.getDefinition().coerce(s);
333
        } catch (CoercionException e) {
334
            throw new IllegalFieldValue(this, "Can't convert value '" + s + "' to '" + this.getDefinition().getDataType().getName() + "'.");
335
        }
336
        this.problemIndicator().clear();
337
        return value;
338
    }
339

    
340
    @SuppressWarnings("unused")
341
    @Override
342
    public boolean hasValidValue() {
343
        try {
344
            Object value = this.getValue();
345
        } catch (Exception e) {
346
            return false;
347
        }
348
        return true;
349
    }
350

    
351
//
352
// Estos metodos los he movido a la superclase.
353
//
354
//    @Override
355
//    public void focusGained(FocusEvent arg0) {
356
//        fireFieldEnterEvent();
357
//        this.problemIndicator().restore();
358
//    }
359
//
360
//    @Override
361
//    public void focusLost(FocusEvent arg0) {
362
//        if (this.hasValidValue()) {
363
//            this.problemIndicator().clear();
364
//        } else {
365
//            try {
366
//                Object value = this.getValue();
367
//            } catch (Exception e) {
368
//                this.problemIndicator().set(e.getLocalizedMessage());
369
//            }
370
//        }
371
//        fireFieldExitEvent();
372
//    }
373
//
374
    /**
375
     * Este m?todo es por si se quiere a?adir una expresi?n regular al
376
     * JTextField Por defecto, se puede escribir cualquier cosa, pero se puede
377
     * sobreescribir este m?todo en la clase que lo requiera para a?adir
378
     * restricciones (p.ej: en los num?ricos)
379
     *
380
     * @return expresi?n regular que filtra el contenido del JTextField
381
     */
382
    public String getJTextFieldRegex() {
383
        return "[*]";
384
    }
385

    
386
    public class KeyAdapterRegEx extends KeyAdapter {
387

    
388
        /**
389
         * Key released on field.
390
         *
391
         * @param e
392
         */
393
        @Override
394
        public void keyReleased(KeyEvent e) {
395
            String curText = ((JTextComponent) e.getSource()).getText();
396
            curText = curText.replaceAll(getJTextFieldRegex(), "");
397

    
398
            ((JTextComponent) e.getSource()).setText(curText);
399
        }
400
    }
401
}