Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / view / legend / gui / VectorialInterval.java @ 11704

History | View | Annotate | Download (34.9 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.project.documents.view.legend.gui;
42

    
43
import java.awt.BorderLayout;
44
import java.awt.Color;
45
import java.awt.Component;
46
import java.awt.FlowLayout;
47
import java.awt.GridLayout;
48
import java.awt.event.ActionEvent;
49
import java.awt.event.ActionListener;
50
import java.io.IOException;
51
import java.sql.Types;
52
import java.text.NumberFormat;
53
import java.util.ArrayList;
54

    
55
import javax.swing.BorderFactory;
56
import javax.swing.DefaultComboBoxModel;
57
import javax.swing.JButton;
58
import javax.swing.JCheckBox;
59
import javax.swing.JComboBox;
60
import javax.swing.JOptionPane;
61
import javax.swing.JPanel;
62
import javax.swing.JTextField;
63

    
64
import org.apache.log4j.Logger;
65
import org.gvsig.gui.beans.swing.GridBagLayoutPanel;
66

    
67
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
68
import com.hardcode.gdbms.engine.data.DataSource;
69
import com.hardcode.gdbms.engine.data.driver.DriverException;
70
import com.hardcode.gdbms.engine.values.DateValue;
71
import com.hardcode.gdbms.engine.values.DoubleValue;
72
import com.hardcode.gdbms.engine.values.FloatValue;
73
import com.hardcode.gdbms.engine.values.IntValue;
74
import com.hardcode.gdbms.engine.values.LongValue;
75
import com.hardcode.gdbms.engine.values.NullValue;
76
import com.hardcode.gdbms.engine.values.Value;
77
import com.iver.andami.PluginServices;
78
import com.iver.andami.messages.NotificationManager;
79
import com.iver.cit.gvsig.fmap.core.FShape;
80
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
81
import com.iver.cit.gvsig.fmap.core.styles.IMarkerFillProperties;
82
import com.iver.cit.gvsig.fmap.core.symbols.IFillSymbol;
83
import com.iver.cit.gvsig.fmap.core.symbols.ILineSymbol;
84
import com.iver.cit.gvsig.fmap.core.symbols.IMarkerSymbol;
85
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
86
import com.iver.cit.gvsig.fmap.core.symbols.PictureMarkerSymbol;
87
import com.iver.cit.gvsig.fmap.core.symbols.SimpleFillSymbol;
88
import com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol;
89
import com.iver.cit.gvsig.fmap.core.symbols.SimpleMarkerSymbol;
90
import com.iver.cit.gvsig.fmap.layers.FLayer;
91
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
92
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
93
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
94
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
95
import com.iver.cit.gvsig.fmap.rendering.FInterval;
96
import com.iver.cit.gvsig.fmap.rendering.IInterval;
97
import com.iver.cit.gvsig.fmap.rendering.ILegend;
98
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
99
import com.iver.cit.gvsig.fmap.rendering.NullIntervalValue;
100
import com.iver.cit.gvsig.fmap.rendering.VectorialIntervalLegend;
101
import com.iver.cit.gvsig.gui.panels.ColorChooserPanel;
102
import com.iver.cit.gvsig.project.documents.view.legend.NaturalIntervalGenerator;
103
import com.iver.cit.gvsig.project.documents.view.legend.QuantileIntervalGenerator;
104

    
105

    
106
/**
107
 * DOCUMENT ME!
108
 *
109
 * @author Vicente Caballero Navarro
110
 */
111
public class VectorialInterval extends JPanel implements ILegendPanel{
112
    private static Logger logger = Logger.getLogger(VectorialInterval.class.getName());
113
    private GridBagLayoutPanel pnlGeneral = null;
114
    protected JComboBox cmbField = null;
115
    protected JTextField txtNumIntervals = null;
116
    private ColorChooserPanel colorChooserPanel = null;
117
    private ColorChooserPanel colorChooserPanel1 = null;
118
    protected JCheckBox chkdefaultvalues = null;
119
    protected JComboBox cmbFieldType = null;
120
    private JPanel panelS = null;
121
    private JButton bintervals = null;
122
    private JButton bInsert = null;
123
    protected JButton bDelAll = null;
124
    protected JButton bDel = null;
125
    private int count = 0;
126
    protected ClassifiableVectorial layer;
127
    protected VectorialIntervalLegend renderer;
128
    protected VectorialIntervalLegend auxLegend = null;
129
    protected FSymbolTable symbolTable;
130
    private MyListener listener = new MyListener();
131
    protected JPanel pnlCenter = null;
132
    private PictureMarkerSymbol previewSymbol;
133
    protected JPanel optionPanel;
134
    private JPanel pnlNorth;
135

    
136
    /**
137
     * This is the default constructor
138
     */
139
    public VectorialInterval() {
140
        super();
141
        initialize();
142
    }
143

    
144
    /**
145
     * This method initializes this
146
     */
147
    private void initialize() {
148
        this.setLayout(new BorderLayout());
149
        this.setSize(490, 300);
150
        this.add(getPnlNorth(), BorderLayout.NORTH);
151

    
152
        this.add(getPnlButtons(), BorderLayout.SOUTH);
153
        this.add(getPnlCenter(), BorderLayout.CENTER);
154
        setOptionPanel(getOptionPanel());
155
    }
156

    
157
    private JPanel getPnlNorth() {
158
        if (pnlNorth == null) {
159
            pnlNorth = new JPanel(new GridLayout(1, 2));
160
            pnlNorth.add(getGeneralPanel());
161
        }
162
        return pnlNorth;
163
    }
164

    
165
    /**
166
     * This method initializes panelN
167
     *
168
     * @return javax.swing.JPanel
169
     */
170
    private JPanel getGeneralPanel() {
171
        if (pnlGeneral == null) {
172
            pnlGeneral = new GridBagLayoutPanel();
173
            pnlGeneral.setBorder(BorderFactory.
174
                    createTitledBorder(null,
175
                            PluginServices.getText(this, "fields")));
176
            pnlGeneral.addComponent(PluginServices.getText(this, "Campo_de_clasificacion"),
177
                    getCmbFields());
178
            pnlGeneral.addComponent(PluginServices.getText(this, "tipo_de_intervalo"),
179
                    getCmbIntervalTypes());
180

    
181
            JPanel aux = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
182
            aux.add(getTxtNumIntervals());
183
            pnlGeneral.addComponent(PluginServices.getText(this, "No_de_intervalos"),
184
                    aux);
185
            pnlGeneral.addComponent("", getChkDefaultvalues());
186

    
187
        }
188
        return pnlGeneral;
189
    }
190

    
191
    public JPanel getOptionPanel() {
192
        if (optionPanel == null) {
193
            optionPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
194
            optionPanel.setBorder(BorderFactory.
195
                    createTitledBorder(null,
196
                            PluginServices.getText(this, "color_ramp")));
197

    
198
            GridBagLayoutPanel aux = new GridBagLayoutPanel();
199
            aux.addComponent(PluginServices.getText(this, "Color_final"),
200
                    getColorChooserPanel());
201
            aux.addComponent(PluginServices.getText(this, "Color_inicio"),
202
                    getColorChooserPanel1());
203
            optionPanel.add(aux);
204
        }
205
        return optionPanel;
206
    }
207

    
208
    private void setOptionPanel(JPanel p) {
209
        getPnlNorth().remove(getOptionPanel());
210
        getPnlNorth().add(p, BorderLayout.NORTH);
211
    }
212
    /**
213
     * This method initializes jComboBox
214
     *
215
     * @return javax.swing.JComboBox
216
     */
217
    private JComboBox getCmbFields() {
218
        if (cmbField == null) {
219
            cmbField = new JComboBox();
220
            cmbField.setActionCommand("FIELD_SELECTED");
221
            cmbField.addActionListener(listener);
222
            cmbField.setVisible(true);
223
        }
224

    
225
        return cmbField;
226
    }
227

    
228
    /**
229
     * This method initializes txtNumIntervals
230
     *
231
     * @return javax.swing.JTextField
232
     */
233
    private JTextField getTxtNumIntervals() {
234
        if (txtNumIntervals == null) {
235
            txtNumIntervals = new JTextField(5);
236
            txtNumIntervals.setText("5");
237
        }
238

    
239
        return txtNumIntervals;
240
    }
241

    
242
    /**
243
     * This method initializes colorChooserPanel
244
     *
245
     * @return com.iver.cit.gvsig.gui.Panels.ColorChooserPanel
246
     */
247
    private ColorChooserPanel getColorChooserPanel() {
248
        if (colorChooserPanel == null) {
249
            colorChooserPanel = new ColorChooserPanel();
250
            colorChooserPanel.setBounds(new java.awt.Rectangle(108, 49, 54, 20));
251
            colorChooserPanel.setAlpha(255);
252
            colorChooserPanel.setColor(Color.red);
253
        }
254

    
255
        return colorChooserPanel;
256
    }
257

    
258
    /**
259
     * This method initializes colorChooserPanel1
260
     *
261
     * @return com.iver.cit.gvsig.gui.Panels.ColorChooserPanel
262
     */
263
    private ColorChooserPanel getColorChooserPanel1() {
264
        if (colorChooserPanel1 == null) {
265
            colorChooserPanel1 = new ColorChooserPanel();
266
            colorChooserPanel1.setBounds(new java.awt.Rectangle(251, 49, 54, 20));
267
            colorChooserPanel1.setAlpha(255);
268
            colorChooserPanel1.setColor(Color.blue);
269
        }
270

    
271
        return colorChooserPanel1;
272
    }
273

    
274
    /**
275
     * This method initializes chkdefaultvalues
276
     *
277
     * @return javax.swing.JCheckBox
278
     */
279
    protected JCheckBox getChkDefaultvalues() {
280
        if (chkdefaultvalues == null) {
281
            chkdefaultvalues = new JCheckBox();
282
            chkdefaultvalues.setText(PluginServices.getText(this,
283
            "resto_valores"));
284
            chkdefaultvalues.setBounds(new java.awt.Rectangle(342, 26, 141, 20));
285
            chkdefaultvalues.addActionListener(new java.awt.event.ActionListener() {
286
                public void actionPerformed(java.awt.event.ActionEvent e) {
287
                    if (auxLegend==null)auxLegend=renderer;
288
                    if (chkdefaultvalues.isSelected()) {
289
                        addDefault();
290
                    } else {
291
                        delDefault();
292
                    }
293
                }
294
            });
295
        }
296

    
297
        return chkdefaultvalues;
298
    }
299

    
300
    /**
301
     * This method initializes jComboBox1
302
     *
303
     * @return javax.swing.JComboBox
304
     */
305
    private JComboBox getCmbIntervalTypes() {
306
        if (cmbFieldType == null) {
307
            cmbFieldType = new JComboBox();
308
            cmbFieldType.setActionCommand("INTERVAL_TYPE");
309
            cmbFieldType.addActionListener(listener);
310
            cmbFieldType.addItem(PluginServices.getText(this, "equal_intervals"));
311
            cmbFieldType.addItem(PluginServices.getText(this,
312
                    "natural_intervals"));
313
            cmbFieldType.addItem(PluginServices.getText(this,
314
                    "quantile_intervals"));
315
            cmbFieldType.setVisible(true);
316
        }
317

    
318
        return cmbFieldType;
319
    }
320

    
321
    /**
322
     * This method initializes panelS
323
     *
324
     * @return javax.swing.JPanel
325
     */
326
    protected JPanel getPnlButtons() {
327
        if (panelS == null) {
328
            panelS = new JPanel();
329
            panelS.setPreferredSize(new java.awt.Dimension(417, 32));
330
            panelS.add(getBintervals(), null);
331
            panelS.add(getBInsert(), null);
332
            panelS.add(getBDelAll(), null);
333
            panelS.add(getBDel(), null);
334
        }
335

    
336
        return panelS;
337
    }
338

    
339
    /**
340
     * This method initializes bintervals
341
     *
342
     * @return javax.swing.JButton
343
     */
344
    private JButton getBintervals() {
345
        if (bintervals == null) {
346
            bintervals = new JButton();
347
            bintervals.setActionCommand("ADD_ALL_VALUES");
348
            bintervals.addActionListener(listener);
349
            bintervals.setText(PluginServices.getText(this,
350
                    "Calcular_intervalos"));
351
        }
352

    
353
        return bintervals;
354
    }
355

    
356
    /**
357
     * This method initializes bInsert
358
     *
359
     * @return javax.swing.JButton
360
     */
361
    private JButton getBInsert() {
362
        if (bInsert == null) {
363
            bInsert = new JButton();
364
            bInsert.setActionCommand("ADD_VALUE");
365
            bInsert.addActionListener(listener);
366
            bInsert.setText(PluginServices.getText(this, "Anadir"));
367
        }
368

    
369
        return bInsert;
370
    }
371

    
372
    /**
373
     * This method initializes bDelAll
374
     *
375
     * @return javax.swing.JButton
376
     */
377
    private JButton getBDelAll() {
378
        if (bDelAll == null) {
379
            bDelAll = new JButton();
380
            bDelAll.setActionCommand("REMOVE_ALL");
381
            bDelAll.addActionListener(listener);
382
            bDelAll.setText(PluginServices.getText(this, "Quitar_todos"));
383
        }
384

    
385
        return bDelAll;
386
    }
387

    
388
    /**
389
     * This method initializes bDel
390
     *
391
     * @return javax.swing.JButton
392
     */
393
    private JButton getBDel() {
394
        if (bDel == null) {
395
            bDel = new JButton();
396
            bDel.setText(PluginServices.getText(this, "Quitar"));
397
            bDel.setActionCommand("REMOVE");
398
            bDel.addActionListener(listener);
399
        }
400

    
401
        return bDel;
402
    }
403

    
404
    private ISymbol newSymbol(int shapeType, Color c) {
405
        ISymbol sym = SymbologyFactory.createDefaultSymbolByShapeType(shapeType);
406

    
407
        if (sym instanceof IMarkerSymbol) {
408
                sym = new SimpleMarkerSymbol();
409
            ((SimpleMarkerSymbol) sym).setColor(c);
410
        }
411

    
412
        if (sym instanceof ILineSymbol) {
413
            sym = new SimpleLineSymbol();
414
            ((SimpleLineSymbol) sym).setLineColor(c);
415
        }
416

    
417
        if (sym instanceof IFillSymbol) {
418
            sym = new SimpleFillSymbol();
419
            ((SimpleFillSymbol) sym).setFillColor(c);
420

    
421
        }
422

    
423
        return sym;
424
    }
425

    
426
    private ISymbol newSymbol(int shapeType) {
427
        ISymbol sym;
428
        switch (shapeType) {
429
        case FShape.POINT:
430
            sym = new SimpleMarkerSymbol();
431
            break;
432

    
433
        case FShape.LINE:
434
            sym = new SimpleLineSymbol();
435
            break;
436

    
437
        case FShape.POLYGON:
438
            sym = new SimpleFillSymbol();
439
            break;
440

    
441
        default:
442
            throw new Error("Unknown symbol type");
443
        }
444

    
445
        return sym;
446
    }
447
    /**
448
     * Damos una primera pasada para saber los l?mites inferior y superior y
449
     * rellenar un array con los valores. Luego dividimos ese array en
450
     * intervalos.
451
     */
452
    protected void fillTableValues() {
453

    
454
        symbolTable.removeAllItems();
455

    
456
        try {
457
            FInterval[] arrayIntervalos = calculateIntervals();
458
            if (arrayIntervalos == null)
459
                    return;
460
            //intervals = arrayIntervalos;
461
            FInterval interval;
462
            NumberFormat.getInstance().setMaximumFractionDigits(2);
463
            renderer.clear();
464

    
465
            int r;
466
            int g;
467
            int b;
468
            int stepR;
469
            int stepG;
470
            int stepB;
471

    
472
            // Cogemos el tipo de gradaci?n de colores que quiere el usuario y
473
            // Creamos el primer y ?ltimo color.
474
            Color startColor = colorChooserPanel.getColor();
475
            renderer.setStartColor(startColor);
476

    
477
            Color endColor = colorChooserPanel1.getColor();
478
            renderer.setEndColor(endColor);
479

    
480
            r = startColor.getRed();
481
            g = startColor.getGreen();
482
            b = startColor.getBlue();
483
            stepR = (endColor.getRed() - r) / arrayIntervalos.length;
484
            stepG = (endColor.getGreen() - g) / arrayIntervalos.length;
485
            stepB = (endColor.getBlue() - b) / arrayIntervalos.length;
486
            ISymbol theSymbol;
487

    
488
            if (chkdefaultvalues.isSelected()) {
489
                auxLegend.getDefaultSymbol().setDescription("Default");
490
                auxLegend.addSymbol(new NullIntervalValue(),
491
                    auxLegend.getDefaultSymbol());
492
            }
493

    
494
            int symbolType = layer.getShapeType();
495
            int numSymbols = 0;
496
            for (int k = 0; k < arrayIntervalos.length; k++) {
497
                interval = arrayIntervalos[k];
498

    
499
                theSymbol = newSymbol(symbolType, new Color(r, g, b));
500
                theSymbol.setDescription(NumberFormat.getInstance().format(interval.getMin()) +
501
                    " - " +
502
                    NumberFormat.getInstance().format(interval.getMax()));
503

    
504
                //////////////////////////////////////
505
                // CALCULAMOS UN COLOR APROPIADO
506
                r = r + stepR;
507
                g = g + stepG;
508
                b = b + stepB;
509

    
510
                /////////////////////////////////
511
                auxLegend.addSymbol(interval, theSymbol);
512
                System.out.println("addSymbol = " + interval +
513
                    " theSymbol = " + theSymbol.getDescription());
514
                numSymbols++;
515

    
516
                if (numSymbols > 100) {
517
                    int resp = JOptionPane.showConfirmDialog(this,
518
                            PluginServices.getText(this, "mas_de_100_simbolos"),
519
                            PluginServices.getText(this, "quiere_continuar"),
520
                            JOptionPane.YES_NO_OPTION,
521
                            JOptionPane.WARNING_MESSAGE);
522

    
523
                    if ((resp == JOptionPane.NO_OPTION) ||
524
                            (resp == JOptionPane.DEFAULT_OPTION)) {
525
                        return;
526
                    }
527
                }
528

    
529
                // }
530
            } // for
531

    
532
            System.out.println("Num. Simbolos = " +
533
                auxLegend.getValues().length);
534
            symbolTable.fillTableFromSymbolList(auxLegend.getSymbols(),
535
                auxLegend.getValues(), auxLegend.getDescriptions());
536

    
537
        } catch (ReadDriverException e) {
538
                NotificationManager.addError(PluginServices.getText(this, "could_not_get_shape_type"), e);
539
        }
540

    
541
        bDelAll.setEnabled(true);
542
        bDel.setEnabled(true);
543
    }
544

    
545
    protected FInterval[] calculateIntervals() {
546
            try {
547
                    FInterval[] intervalArray = null;
548
                    DataSource recordSet;
549
                    recordSet = ((AlphanumericData) layer).getRecordset();
550
                    logger.debug("elRs.start()");
551
                    recordSet.start();
552

    
553
                    int idField = -1;
554
                    int numIntervalos = 1;
555

    
556
                    try {
557
                            numIntervalos = Integer.parseInt(txtNumIntervals.getText());
558
                    } catch (NumberFormatException e) {
559
                            System.out.println("Foramto de n?mero erroneo");
560
                    }
561

    
562
                    String fieldName = (String) cmbField.getSelectedItem();
563
                    if (fieldName==null) {
564
                            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_hay_campo_seleccionado"));
565
                            return null;
566
                    }
567
                    renderer.setFieldNames(new String[] {fieldName});
568

    
569
                    String[] nomField = renderer.getFieldNames();
570

    
571

    
572
                    for (int i = 0; i < recordSet.getFieldCount(); i++) {
573
                            String nomAux = recordSet.getFieldName(i).trim();
574

    
575
                            if (nomField[0].compareToIgnoreCase(nomAux) == 0) {
576
                                    idField = i;
577

    
578
                                    break;
579
                            }
580
                    }
581

    
582
                    if (idField == -1) {
583
                            logger.error("Campo no reconocido " + nomField);
584

    
585
                            return null;
586
                    }
587

    
588
                    //Date valorDate;
589
                    double minValue = Double.MAX_VALUE;
590
                    double maxValue = Double.NEGATIVE_INFINITY;
591

    
592
                    //Date minValueDate = null;
593
                    //Date maxValueDate = null;
594
                    auxLegend = LegendFactory.createVectorialIntervalLegend(layer.getShapeType());
595

    
596
                    Value clave;
597

    
598
                    //Object resul;
599
                    count = 0;
600

    
601
                    for (int j = 0; j < recordSet.getRowCount(); j++) {
602
                            clave = recordSet.getFieldValue(j, idField);
603

    
604
                            IInterval interval = auxLegend.getInterval(clave);
605

    
606
                            ////Comprobar que no esta repetido y no hace falta introducir en el hashtable el campo junto con el simbolo.
607
                            if (auxLegend.getSymbolByInterval(interval) == null) {
608
                                    //si no esta creado el simbolo se crea
609
                                    double valor = 0;
610

    
611

    
612
                                    if (clave instanceof IntValue) {
613
                                            valor = ((IntValue) clave).getValue();
614
                                    } else if (clave instanceof DoubleValue) {
615
                                            valor = ((DoubleValue) clave).getValue();
616
                                    } else if (clave instanceof FloatValue) {
617
                                            valor = ((FloatValue) clave).getValue();
618
                                    } else if (clave instanceof LongValue) {
619
                                            valor = ((LongValue) clave).getValue();
620
                                    } else if (clave instanceof DateValue) {
621
                                            //TODO POR IMPLEMENTAR
622
                                            ///valorDate = elRs.getFieldValueAsDate(idField);
623
                                            ///if (valorDate.before(minValueDate)) minValueDate = valorDate;
624
                                            ///if (valorDate.after(maxValueDate)) maxValueDate = valorDate;
625
                                    } else if (clave instanceof NullValue) {
626
                                            continue;
627
                                    }
628

    
629
                                    if (valor < minValue) {
630
                                            minValue = (double) valor;
631
                                    }
632

    
633
                                    if (valor > maxValue) {
634
                                            maxValue = (double) valor;
635
                                    }
636
                            }
637

    
638
                            count++;
639
                    }
640

    
641
                    switch (renderer.getIntervalType()) {
642
                    case VectorialIntervalLegend.EQUAL_INTERVALS:
643
                            intervalArray = calculateEqualIntervals(numIntervalos,
644
                                            minValue, maxValue, fieldName);
645

    
646
                            break;
647

    
648
                    case VectorialIntervalLegend.NATURAL_INTERVALS:
649
                            intervalArray = calculateNaturalIntervals(numIntervalos,
650
                                            minValue, maxValue, fieldName);
651

    
652
                            break;
653

    
654
                    case VectorialIntervalLegend.QUANTILE_INTERVALS:
655
                            intervalArray = calculateQuantileIntervals(numIntervalos,
656
                                            minValue, maxValue, fieldName);
657

    
658
                            break;
659
                    }
660
                    recordSet.stop();
661
                    return intervalArray;
662
            } catch (ReadDriverException e) {
663
                    return null;
664
            }
665
    }
666

    
667
    /**
668
     * EQUAL INTERVAL Devuelve un Array con el n?mero de intervalos que se
669
     * quieren crear. Los intervalos se crean con un tama?o igual entre ellos.
670
     *
671
     * @param numIntervals n?mero de intervalos
672
     * @param minValue Valor m?nimo.
673
     * @param maxValue Valor m?ximo.
674
     * @param fieldName Nombre del campo
675
     *
676
     * @return Array con los intervalos.
677
     */
678
    private FInterval[] calculateEqualIntervals(int numIntervals, double minValue,
679
        double maxValue, String fieldName) {
680
        FInterval[] theIntervalArray = new FInterval[numIntervals];
681
        double step = (maxValue - minValue) / numIntervals;
682

    
683
        if (numIntervals > 1) {
684
            theIntervalArray[0] = new FInterval(minValue, minValue + step);
685

    
686
            for (int i = 1; i < (numIntervals - 1); i++) {
687
                theIntervalArray[i] = new FInterval(minValue + (i * step) +
688
                        0.01, minValue + ((i + 1) * step));
689
            }
690

    
691
            theIntervalArray[numIntervals - 1] = new FInterval(minValue +
692
                    ((numIntervals - 1) * step) + 0.01, maxValue);
693
        } else {
694
            theIntervalArray[0] = new FInterval(minValue, maxValue);
695
        }
696

    
697
        return theIntervalArray;
698
    }
699

    
700
    /**
701
     * NATURAL INTERVAL Devuelve un Array con el n?mero de intervalos que se
702
     * quieren crear. Los intervalos se distribuyen de forma natural.
703
     *
704
     * @param numIntervals n?mero de intervalos
705
     * @param minValue Valor m?nimo.
706
     * @param maxValue Valor m?ximo.
707
     * @param fieldName Nombre del campo
708
     *
709
     * @return Array con los intervalos.
710
     */
711
    private FInterval[] calculateNaturalIntervals(int numIntervals, double minValue,
712
        double maxValue, String fieldName) {
713
        NaturalIntervalGenerator intervalGenerator = new NaturalIntervalGenerator(((AlphanumericData) layer),
714
                fieldName, numIntervals);
715

    
716
        try {
717
            intervalGenerator.generarIntervalos();
718
        } catch (ReadDriverException e) {
719
                NotificationManager.addError(PluginServices.getText(this, "generating_intervals"), e);
720
        }
721

    
722
        int numIntervalsGen = intervalGenerator.getNumIntervals() - 1;
723

    
724
        if (numIntervalsGen == -1) {
725
            //TODO cuando no puede calcular los intervalos.
726
            numIntervalsGen = 1;
727
        }
728

    
729
        FInterval[] theIntervalArray = new FInterval[numIntervalsGen];
730

    
731
        if (numIntervalsGen > 1) {
732
            theIntervalArray[0] = new FInterval(minValue,
733
                    intervalGenerator.getValorRuptura(0));
734

    
735
            for (int i = 1; i < (numIntervalsGen - 1); i++) {
736
                theIntervalArray[i] = new FInterval(intervalGenerator.getValInit(i -
737
                            1), intervalGenerator.getValorRuptura(i));
738
            }
739

    
740
            theIntervalArray[numIntervalsGen - 1] = new FInterval(intervalGenerator.getValInit(numIntervalsGen -
741
                        2), maxValue);
742
        } else {
743
            theIntervalArray[numIntervalsGen - 1] = new FInterval(minValue,
744
                    maxValue);
745
        }
746

    
747
        return theIntervalArray;
748
    }
749

    
750
    /**
751
     * QUANTILE INTERVAL Devuelve un Array con el n?mero de intervalos que se
752
     * quieren crear. Los intervalos se distribuyen de forma quantile.
753
     *
754
     * @param numIntervals n?mero de intervalos
755
     * @param minValue Valor m?nimo.
756
     * @param maxValue Valor m?ximo.
757
     * @param fieldName Nombre del campo
758
     *
759
     * @return Array con los intervalos.
760
     */
761
    private FInterval[] calculateQuantileIntervals(int numIntervals, double minValue,
762
        double maxValue, String fieldName) {
763
        QuantileIntervalGenerator intervalGenerator = new QuantileIntervalGenerator(((AlphanumericData) layer),
764
                fieldName, numIntervals);
765

    
766
        try {
767
            intervalGenerator.generarIntervalos();
768
        } catch (ReadDriverException e) {
769
                NotificationManager.addError(PluginServices.getText(this, "generating_intervals"), e);
770
        }
771

    
772
        int numIntervalsGen = intervalGenerator.getNumIntervalGen();
773
        FInterval[] theIntervalArray = new FInterval[numIntervalsGen];
774

    
775
        if (intervalGenerator.getNumIntervalGen() > 1) {
776
            theIntervalArray[0] = new FInterval(minValue,
777
                    intervalGenerator.getValRuptura(0));
778

    
779
            for (int i = 1; i < (numIntervalsGen - 1); i++) {
780
                theIntervalArray[i] = new FInterval(intervalGenerator.getValInit(i -
781
                            1), intervalGenerator.getValRuptura(i));
782
            }
783

    
784
            theIntervalArray[numIntervalsGen - 1] = new FInterval(intervalGenerator.getValInit(numIntervalsGen -
785
                        2), maxValue);
786
        } else {
787
            theIntervalArray[numIntervalsGen - 1] = new FInterval(minValue,
788
                    maxValue);
789
        }
790

    
791
        return theIntervalArray;
792
    }
793

    
794
    /**
795
     * @see com.iver.cit.gvsig.gui.legendmanager.panels.ILegendPanel#setData(com.iver.cit.gvsig.fmap.layers.FLayer,
796
     *      com.iver.cit.gvsig.fmap.rendering.ILegend)
797
     */
798
    public void setData(FLayer layer, ILegend legend) {
799
        this.layer = (ClassifiableVectorial) layer;
800
            int shapeType = 0;
801
            try {
802
                    shapeType = this.layer.getShapeType();
803
            } catch (ReadDriverException e) {
804
                    NotificationManager.addError(PluginServices.getText(this, "generating_intervals"), e);
805
            }
806

    
807
            if (symbolTable != null)
808
                      pnlCenter.remove(symbolTable);
809

    
810

    
811
            symbolTable = new FSymbolTable("intervals", shapeType);
812
            pnlCenter.add(symbolTable);
813
        fillFieldNames();
814

    
815
        if (legend instanceof VectorialIntervalLegend) {
816
            renderer = (VectorialIntervalLegend) legend;
817
            getChkDefaultvalues().setSelected(renderer.isUseDefaultSymbol());
818
            cmbField.getModel().setSelectedItem(renderer.getFieldNames()[0]);
819
            symbolTable.fillTableFromSymbolList(renderer.getSymbols(),
820
                renderer.getValues(), renderer.getDescriptions());
821
            colorChooserPanel.setColor(renderer.getStartColor());
822
            colorChooserPanel1.setColor(renderer.getEndColor());
823
            colorChooserPanel.repaint();
824
            colorChooserPanel1.repaint();
825
        } else {
826
                        // Si la capa viene con otro tipo de leyenda, creamos
827
                        // una nueva del tipo que maneja este panel
828
                        renderer = new VectorialIntervalLegend();
829
        }
830

    
831
        cmbFieldType.setSelectedIndex(renderer.getIntervalType());
832
    }
833

    
834
    /**
835
     * DOCUMENT ME!
836
     */
837
    protected void fillFieldNames() {
838
        DataSource rs = null;
839
        ArrayList nomFields = null;
840

    
841
        try {
842
            rs = ((AlphanumericData) layer).getRecordset();
843
            logger.debug("rs.start()");
844
            rs.start();
845

    
846
            nomFields = new ArrayList();
847

    
848
            int type;
849
            for (int i = 0; i < rs.getFieldCount(); i++) {
850
                type = rs.getFieldType(i);
851

    
852
                if (type == Types.NULL) {
853
                    continue;
854
                }
855

    
856
                if ((type == Types.INTEGER) ||
857
                        (type == Types.DOUBLE) ||
858
                        (type == Types.FLOAT) ||
859
                        (type == Types.BIGINT)) {
860
                    nomFields.add(rs.getFieldName(i).trim());
861
                }
862
            }
863

    
864
            rs.stop();
865
        } catch (ReadDriverException e) {
866
                NotificationManager.addError(PluginServices.getText(this, "recovering_recordset"), e);
867
        }
868

    
869
        DefaultComboBoxModel cM = new DefaultComboBoxModel(nomFields.toArray());
870
        cmbField.setModel(cM);
871

    
872
        symbolTable.removeAllItems();
873
    }
874

    
875
    /**
876
     * @see com.iver.cit.gvsig.gui.legendmanager.panels.ILegendPanel#getLegend()
877
     */
878
    public ILegend getLegend() {
879
        fillSymbolListFromTable();
880

    
881
        if (auxLegend != null) {
882
            renderer.setDefaultSymbol(auxLegend.getDefaultSymbol());
883
            renderer.useDefaultSymbol(chkdefaultvalues.isSelected());
884
        }
885

    
886
        return renderer;
887
    }
888

    
889
    /**
890
     * A partir de los registros de la tabla, regenera el FRenderer. (No solo
891
     * el symbolList, si no tambi?n el arrayKeys y el defaultRenderer
892
     */
893
    private void fillSymbolListFromTable() {
894
        ISymbol theSymbol;
895
        IInterval theInterval = null;
896

    
897
        // Borramos las anteriores listas:
898
        renderer.clear();
899

    
900
        String fieldName = (String) cmbField.getSelectedItem();
901
        renderer.setFieldNames(new String[] {fieldName});
902

    
903
        for (int row = 0; row < symbolTable.getRowCount(); row++) {
904
            if (!(symbolTable.getFieldValue(row, 1) instanceof FInterval)) {
905
                theSymbol = (ISymbol) symbolTable.getFieldValue(row, 0);
906
                theSymbol.setDescription((String) symbolTable.getFieldValue(
907
                        row, 2));
908
                renderer.addSymbol(new NullIntervalValue(), theSymbol);
909
            } else {
910
                theInterval = (IInterval) symbolTable.getFieldValue(row, 1);
911
                theSymbol = (ISymbol) symbolTable.getFieldValue(row, 0);
912
                theSymbol.setDescription((String) symbolTable.getFieldValue(
913
                        row, 2));
914
                renderer.addSymbol(theInterval, theSymbol);
915
            }
916

    
917
        }
918
    }
919

    
920
    /**
921
     * This method initializes panelC
922
     *
923
     * @return javax.swing.JPanel
924
     */
925
    private JPanel getPnlCenter() {
926
        if (pnlCenter == null) {
927
            pnlCenter = new JPanel();
928
        }
929

    
930
        return pnlCenter;
931
    }
932

    
933
    /**
934
     * A?ade la fila y el s?mbolo para el resto de valores no representados.
935
     */
936
    private void addDefault() {
937

    
938
        auxLegend.getDefaultSymbol().setDescription("Default");
939
        auxLegend.addSymbol(new NullIntervalValue(),
940
            auxLegend.getDefaultSymbol());
941
        symbolTable.addTableRecord(auxLegend.getDefaultSymbol(),
942
            new NullIntervalValue(),
943
            auxLegend.getDefaultSymbol().getDescription());
944
        symbolTable.repaint();
945
    }
946

    
947
    /**
948
     * Elimina la fila de la tabla y el s?mbolo del resto de valores no
949
     * representados por ning?n valor.
950
     */
951
    private void delDefault() {
952
        auxLegend.delSymbol(new NullIntervalValue());
953
        symbolTable.removeRow(new NullIntervalValue());
954
        symbolTable.repaint();
955
    }
956

    
957
    /**
958
     * Listener.
959
     *
960
     * @author Vicente Caballero Navarro
961
     */
962
    class MyListener implements ActionListener {
963

    
964
       public void actionPerformed(ActionEvent e) {
965
            System.out.println("ActionEvent con " + e.getActionCommand());
966

    
967
            //modificar el combobox de valor
968
            if (e.getActionCommand() == "FIELD_SELECTED") {
969
                JComboBox cb = (JComboBox) e.getSource();
970
                String fieldName = (String) cb.getSelectedItem();
971
                System.out.println("Nombre del campo: " + fieldName);
972
                symbolTable.removeAllItems();
973

    
974
                renderer.setFieldNames(new String[] {fieldName});
975
            } else if (e.getActionCommand() == "INTERVAL_TYPE") {
976
                JComboBox cb = (JComboBox) e.getSource();
977

    
978
                if ((renderer != null) &&
979
                        (cb.getSelectedIndex() != renderer.getIntervalType())) {
980
                    renderer.setIntervalType(cb.getSelectedIndex());
981
                    symbolTable.removeAllItems();
982
                }
983
            }
984

    
985
            //A?adir todos los elementos por valor
986
            if (e.getActionCommand() == "ADD_ALL_VALUES") {
987
                fillTableValues();
988
            }
989

    
990
            //A?adir un ?nico elemento
991
            if (e.getActionCommand() == "ADD_VALUE") {
992
                try {
993
                    symbolTable.addTableRecord(newSymbol(
994
                            layer.getShapeType()), new FInterval(0, 0), "0 - 0");
995
                } catch (ReadDriverException e1) {
996
                        NotificationManager.addError(PluginServices.getText(this, "could_not_get_shape_type"), e1);
997
                }
998

    
999
            }
1000

    
1001
            //Vacia la tabla
1002
            if (e.getActionCommand() == "REMOVE_ALL") {
1003
                symbolTable.removeAllItems();
1004

    
1005
            }
1006

    
1007
            //Quitar solo el elemento seleccionado
1008
            if (e.getActionCommand() == "REMOVE") {
1009
                symbolTable.removeSelectedRows();
1010
            }
1011
        }
1012
    }
1013

    
1014
    public String getDescription() {
1015
        return PluginServices.getText(this,"Muestra_los_elementos_de_la_capa_usando_una_gama_de_colores_en_funcion_del_valor_de_un_determinado_campo_de_atributos") + ".";
1016
    }
1017

    
1018
    public ISymbol getPreviewSymbol() {
1019
        if (previewSymbol == null) {
1020
            try {
1021
                previewSymbol = new PictureMarkerSymbol(
1022
                        this.getClass().getClassLoader()
1023
                                .getResource("images/Intervalos.png"));
1024
            } catch (IOException e) {
1025
                return null;
1026
            }
1027
        }
1028
        return previewSymbol;
1029
    }
1030

    
1031
    public Class getParentClass() {
1032
        return Quantities.class;
1033
    }
1034

    
1035
    public String getTitle() {
1036
        return PluginServices.getText(this,"Intervalos");
1037
    }
1038

    
1039
    public JPanel getPanel() {
1040
        return this;
1041
    }
1042

    
1043
    public Class getLegendClass() {
1044
        return VectorialIntervalLegend.class;
1045
    }
1046

    
1047
    private boolean isNumericField(int fieldType) {
1048
                switch (fieldType) {
1049
                case Types.BIGINT:
1050
                case Types.DECIMAL:
1051
                case Types.DOUBLE:
1052
                case Types.FLOAT:
1053
                case Types.INTEGER:
1054
                case Types.NUMERIC:
1055
                case Types.REAL:
1056
                case Types.SMALLINT:
1057
                case Types.TINYINT:
1058
                        return true;
1059
                default:
1060
                        return false;
1061
                }
1062

    
1063
        }
1064
        public boolean isSuitableFor(FLayer layer) {
1065
                if (layer instanceof FLyrVect) {
1066
                        SelectableDataSource sds;
1067
                        try {
1068
                                sds = ((FLyrVect) layer).getRecordset();
1069
                                String[] fNames = sds.getFieldNames();
1070
                                for (int i = 0; i < fNames.length; i++) {
1071
                                        if (isNumericField(sds.getFieldType(i))) {
1072
                                                return true;
1073
                                        }
1074
                                }
1075
                        } catch (ReadDriverException e) {
1076
                                return false;
1077
                        }
1078
                }
1079
                return false;
1080
        }
1081
}