Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / gui / thememanager / FThemeManagerWindow.java @ 2381

History | View | Annotate | Download (18 KB)

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

    
46
import java.awt.BorderLayout;
47
import java.awt.Component;
48
import java.awt.event.ActionEvent;
49
import java.awt.event.ActionListener;
50
import java.io.File;
51
import java.io.FileNotFoundException;
52
import java.io.FileReader;
53
import java.io.FileWriter;
54
import java.text.NumberFormat;
55
import java.text.ParseException;
56

    
57
import javax.swing.JButton;
58
import javax.swing.JDialog;
59
import javax.swing.JFileChooser;
60
import javax.swing.JOptionPane;
61
import javax.swing.JPanel;
62
import javax.swing.JTabbedPane;
63

    
64
import org.exolab.castor.xml.MarshalException;
65
import org.exolab.castor.xml.Marshaller;
66
import org.exolab.castor.xml.ValidationException;
67

    
68
import com.hardcode.gdbms.engine.data.DataSource;
69
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
70
import com.iver.andami.PluginServices;
71
import com.iver.andami.messages.Messages;
72
import com.iver.andami.messages.NotificationManager;
73
import com.iver.andami.ui.mdiManager.View;
74
import com.iver.andami.ui.mdiManager.ViewInfo;
75
import com.iver.cit.gvsig.fmap.DriverException;
76
import com.iver.cit.gvsig.fmap.FMap;
77
import com.iver.cit.gvsig.fmap.layers.FLayer;
78
import com.iver.cit.gvsig.fmap.layers.XMLException;
79
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
80
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
81
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
82
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegend;
83
import com.iver.cit.gvsig.fmap.rendering.Legend;
84
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
85
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
86
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
87
import com.iver.cit.gvsig.gui.thememanager.legendmanager.FPanelLegendManager;
88
import com.iver.cit.gvsig.gui.thememanager.scalemanager.FPanelScaleManager;
89
import com.iver.utiles.GenericFileFilter;
90
import com.iver.utiles.XMLEntity;
91
import com.iver.utiles.xmlEntity.generate.XmlTag;
92

    
93
/**
94
 * @author jmorell (jose.morell@gmail.com)
95
 * @version 24-ene-2005
96
 */
97
public final class FThemeManagerWindow extends JPanel implements View {
98
        private FMap mapContext;
99
        private FLayer layer;
100
    private Legend renderer; // Le asignaremos la leyenda del primer tema activo.
101
        private FPanelScaleManager fPanelScaleManager;
102
    private FPanelLegendManager fPanelLegendManager;
103
    private JTabbedPane organizador = new JTabbedPane();  //  @jve:decl-index=0:
104
    private ComandosListener m_actionListener = new ComandosListener(this);
105
        //private ProjectView view;
106
        private NumberFormat nf = NumberFormat.getInstance();
107

    
108
    /**
109
     * Creates new form JPanel
110
     */
111
    public FThemeManagerWindow() {
112
        initialize();
113
                this.setSize(650, 420);
114
    }
115
    
116
    /**
117
     * Sobrecarga del constructor. Este se utiliza cuando se llama a este
118
     * di?logo desde la barra de comandos.
119
     *
120
     */
121
    public FThemeManagerWindow(FLayer l, FMap fMap) {
122
            initialize();
123
            layer = l;
124
            mapContext = fMap;
125
                try {
126
                        ClassifiableVectorial aux = (ClassifiableVectorial) layer;
127
                        renderer = (Legend) aux.getLegend().cloneLegend();
128
                        fPanelScaleManager.setMapContext(mapContext);
129
                        fPanelLegendManager.setMapContext(mapContext);
130
                } catch (XMLException e) {
131
                        // TODO Auto-generated catch block
132
                        e.printStackTrace();
133
                } catch (DriverException e1) {
134
                        // TODO Auto-generated catch block
135
                        e1.printStackTrace();
136
                }
137
                
138
        fPanelScaleManager.setLayer(layer, renderer);
139
        fPanelLegendManager.setLayer(layer, renderer);
140

    
141
        organizador.setSelectedIndex(0);
142
        
143
                this.setSize(650, 420);
144
    }
145
        
146
        /**
147
         * This method initializes this
148
         * 
149
         * @return void
150
         */
151
        private  void initialize() {
152
                
153
                fPanelScaleManager = new FPanelScaleManager();
154
                fPanelLegendManager = new FPanelLegendManager();
155
                
156
                organizador.addTab(PluginServices.getText(this,"General"), fPanelScaleManager);
157
                organizador.addTab(PluginServices.getText(this,"Simbologia"), fPanelLegendManager);
158
                
159
        JPanel panelButtons = new JPanel();
160
                
161
        JButton btnAceptar = new JButton(PluginServices.getText(this,"Aceptar"));
162
        btnAceptar.setActionCommand("OK");
163
        btnAceptar.addActionListener(m_actionListener);
164

    
165
        JButton btnApply = new JButton(PluginServices.getText(this,"Aplicar"));
166
        btnApply.setActionCommand("APPLY");
167
        btnApply.addActionListener(m_actionListener);
168
        
169
        JButton btnSaveLegend = new JButton(PluginServices.getText(this,"Guardar_leyenda")+"...");
170
        btnSaveLegend.setActionCommand("SAVE_LEGEND");
171
        btnSaveLegend.addActionListener(m_actionListener);
172

    
173
        JButton btnLoadLegend = new JButton(PluginServices.getText(this,"Recuperar_leyenda")+"...");
174
        btnLoadLegend.setActionCommand("LOAD_LEGEND");
175
        btnLoadLegend.addActionListener(m_actionListener);
176
        
177
        JButton btnCancelar = new JButton(PluginServices.getText(this,"Cerrar"));
178
        btnCancelar.setActionCommand("CANCEL");
179
        btnCancelar.addActionListener(m_actionListener);
180
        
181
        panelButtons.add(btnApply, null);
182
        
183
                setLayout(new BorderLayout());
184
                panelButtons.setLayout(null);
185
                organizador.setPreferredSize(new java.awt.Dimension(640,390));
186
                btnAceptar.setBounds(9, 5, 89, 23);
187
                btnApply.setBounds(107, 5, 89, 23);
188
                btnSaveLegend.setBounds(205, 5, 159, 23);
189
                btnLoadLegend.setBounds(373, 5, 159, 23);
190
                btnCancelar.setBounds(541, 5, 89, 23);
191
                panelButtons.setPreferredSize(new java.awt.Dimension(493,33));
192
                add(organizador, java.awt.BorderLayout.NORTH);
193
                panelButtons.add(btnAceptar, null);
194
                add(panelButtons, java.awt.BorderLayout.SOUTH);
195
                panelButtons.add(btnSaveLegend, null);
196
                panelButtons.add(btnLoadLegend, null);
197
                panelButtons.add(btnCancelar, null);
198
        }
199
        
200
        /**
201
         * Cuando hay varios temas vectoriales seleccionados, devolver? el
202
         * ?ltimo.
203
         * @return
204
         */
205
    private FLayer getFirstActiveLayerVect() {
206
        // Comprobar en openLegendManager que hay alg?n tema activo!
207
        FLayer[] activeLyrs = mapContext.getLayers().getActives();
208
        if (activeLyrs.length == 0) {
209
                JOptionPane.showMessageDialog(null, 
210
                                Messages.getString(PluginServices.getText(this, "necesita_un_tema_activo")), "", JOptionPane.ERROR_MESSAGE);
211
                return null;
212
        }
213
        FLayer lyr = null;
214
        for (int i=0; i < activeLyrs.length; i++) {
215
                if (activeLyrs[i] instanceof Classifiable) {
216
                        Classifiable auxC = (Classifiable) activeLyrs[i]; 
217
                        Legend theLegend = auxC.getLegend();
218
                        if (theLegend instanceof VectorialLegend)
219
                                lyr = (FLayer) auxC;        
220
                }
221
        }        
222
        if (lyr == null) {
223
            System.out.println(PluginServices.getText(this,"Por_favor_active_el_tema")+".");
224
                JOptionPane.showMessageDialog(null, 
225
                                Messages.getString(PluginServices.getText(this,"necesita_un_tema_vectorial_activo")), "", JOptionPane.ERROR_MESSAGE);
226
            return null;
227
        }
228
        return lyr;
229
    }
230
    
231
    /**
232
     * En esta funci?n se coge el primer tema activo del TOC y se usa su
233
     * renderer para inicializar. Hay que llamarla SIEMPRE que se abra el
234
     * cuadro de di?logo, en el  openLegendManager() de la vista.
235
     *
236
     * @param mapContext TOC que abre este cuadro de di?logo.
237
     * @throws DriverException
238
     */
239
    public void setMapContext(FMap mapContext) throws DriverException {
240
        this.mapContext = mapContext;
241
        layer = getFirstActiveLayerVect();
242
                try {
243
                        ClassifiableVectorial aux = (ClassifiableVectorial) layer;
244
                        renderer = (Legend) aux.getLegend().cloneLegend();
245
                } catch (XMLException e) {
246
                        // TODO Auto-generated catch block
247
                        e.printStackTrace();
248
                }
249
                fPanelScaleManager.setMapContext(mapContext);
250
                fPanelLegendManager.setMapContext(mapContext);
251
        actualizar();
252
    }
253
    
254
    /**
255
     * DOCUMENT ME!
256
     */
257
    private void actualizar() {
258
            FLayer lyrSelected = getFirstActiveLayerVect();
259
            
260
        fPanelScaleManager.setLayer(lyrSelected, renderer);
261
        fPanelLegendManager.setLayer(lyrSelected, renderer);
262

    
263
        organizador.setSelectedIndex(0);
264
    }
265
        
266
    private void btnApply_actionPerformed(ActionEvent evt) {
267
        ClassifiableVectorial aux = (ClassifiableVectorial) layer;
268
        switch (fPanelLegendManager.getVisibleCard()) {
269
        case 0: // default symbol
270
            renderer = fPanelLegendManager.getM_defaultLegendPanel().getLegend();
271
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + PluginServices.getText(this,"_(Simbolo_unico)"));
272
            break;
273
        case 1: // Unique Values
274
            renderer = fPanelLegendManager.getM_valuesLegendPanel().getLegend();
275
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Valores_unicos)");
276
            break;
277
        case 2:// break values
278
                   renderer = fPanelLegendManager.getM_breaksLegendPanel().getLegend();
279
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Intervalos)");
280
                   break;
281
        case 3://text
282
                renderer = fPanelLegendManager.getM_labelsLegendPanel().getLegend();
283
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Etiquetas_estandar)");
284
        }
285
        try {
286
                        // Intentamos aplicar la leyenda a todas
287
            // las capas activas a las que se les pueda aplicar
288
            FLayer[] activeLyrs =  mapContext.getLayers().getActives();
289
            for (int i=0; i < activeLyrs.length; i++)
290
            {
291
                if (activeLyrs[i] instanceof ClassifiableVectorial)
292
                {
293
                    ClassifiableVectorial aux2 = (ClassifiableVectorial) activeLyrs[i];
294
                    if (renderer instanceof ClassifiedLegend)
295
                    {
296
                        // Es una leyenda que necesita un recordset con un
297
                        // nombre de campo. Comprobamos que ese recordset
298
                        // tiene ese nombre de campo y es del tipo esperado
299
                        ClassifiedLegend cl = (ClassifiedLegend) renderer;
300
                        if (aux2 instanceof AlphanumericData)
301
                        {
302
                            DataSource rs = ((AlphanumericData) aux2).getRecordset();
303
                            int idField = rs.getFieldIndexByName(cl.getFieldName()); 
304
                            if (idField != -1)
305
                            {
306
                                //TODO: Aqu? deber?amos comprobar si el tipo de campo
307
                                // es el tipo de campo esperado.
308
                                aux2.setLegend((VectorialLegend) renderer);
309
                            }
310
                                
311
                        }
312
                    }
313
                    else if (renderer instanceof SingleSymbolLegend)
314
                        aux2.setLegend((VectorialLegend) renderer);
315
                }
316
                     
317
            }
318
                        // aux.setLegend((VectorialLegend) m_Renderer);
319
 
320
                } catch (FieldNotFoundException e) {
321
                        // TODO Auto-generated catch block
322
                        e.printStackTrace();
323
                } catch (DriverException e) {
324
                        // TODO Auto-generated catch block
325
                        e.printStackTrace();
326
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
327
            // TODO Auto-generated catch block
328
            e.printStackTrace();
329
        }
330

    
331
                if (fPanelScaleManager.getJRadioButton1().isSelected()) {
332
                        try
333
                        {
334
                                layer.setMinScale((nf.parse(fPanelScaleManager.getJTextField1().getText())).doubleValue());                                                
335
                        }
336
                        catch (ParseException ex)
337
                        {
338
                            if (fPanelScaleManager.getJTextField1().getText().compareTo("") == 0)
339
                                layer.setMinScale(-1);
340
                            else
341
                                System.err.print(ex.getLocalizedMessage());
342
                        }
343
                        try
344
                        {
345
                            layer.setMaxScale((nf.parse(fPanelScaleManager.getJTextField2().getText())).doubleValue());                                                
346
                        }
347
                        catch (ParseException ex)
348
                        {
349
                            if (fPanelScaleManager.getJTextField2().getText().compareTo("") == 0)
350
                                layer.setMaxScale(-1);
351
                            else
352
                                System.err.print(ex.getLocalizedMessage());
353
                        }                
354
                        
355
                } else {
356
                layer.setMinScale(-1);
357
                layer.setMaxScale(-1);
358
                }
359
                layer.setName(fPanelScaleManager.getLayerName());
360
                layer.getFMap().invalidate();
361
    }
362
        
363
    /**
364
     * DOCUMENT ME!
365
     *
366
     * @author Fernando Gonz?lez Cort?s
367
     */
368
    private class ComandosListener implements ActionListener {
369
        private FThemeManagerWindow fLayerPropertiesWindow;
370

    
371
        /**
372
         * Creates a new ComandosListener object.
373
         *
374
         * @param lg DOCUMENT ME!
375
         */
376
        public ComandosListener(FThemeManagerWindow fLayerPropertiesWindow) {
377
                this.fLayerPropertiesWindow = fLayerPropertiesWindow;
378
        }
379

    
380
        /* (non-Javadoc)
381
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
382
         */
383
        public void actionPerformed(ActionEvent e) {
384
            if (e.getActionCommand() == "OK") {
385
                fLayerPropertiesWindow.btnApply_actionPerformed(e);
386
                    if (PluginServices.getMainFrame() == null)
387
                            ((JDialog) (getParent().getParent().getParent().getParent())).dispose();
388
                    else                
389
                            PluginServices.getMDIManager().closeView(FThemeManagerWindow.this);
390
                System.out.println("Ok");
391
            } else if (e.getActionCommand() == "CANCEL") {
392
                    if (PluginServices.getMainFrame() == null)
393
                            ((JDialog) (getParent().getParent().getParent().getParent())).dispose();
394
                    else
395
                            PluginServices.getMDIManager().closeView(FThemeManagerWindow.this);
396
                System.out.println("CANCEL");
397
            } else if (e.getActionCommand() == "APPLY") {
398
                fLayerPropertiesWindow.btnApply_actionPerformed(e);
399
                System.out.println("APPLY");
400
            } else if (e.getActionCommand() == "LOAD_LEGEND") {
401
                        JFileChooser jfc = new JFileChooser();
402
                            jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
403
                                            PluginServices.getText(this, "tipo_de_leyenda")));
404

    
405
                            if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
406
                                    File file=jfc.getSelectedFile();
407
                                    if (!(file.getPath().endsWith(".gvl") || file.getPath().endsWith(".GVL"))){
408
                                            file=new File(file.getPath()+".gvl");
409
                                    }
410
                                    readLegend(file);
411
                                    fPanelLegendManager.actualizar();
412
                            }
413
            } else if (e.getActionCommand() == "SAVE_LEGEND") {
414
                                fLayerPropertiesWindow.btnApply_actionPerformed(e);
415
                                JFileChooser jfc = new JFileChooser();
416
                                jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
417
                                                PluginServices.getText(this, "tipo_de_leyenda")));
418

    
419
                                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
420
                                        File file=jfc.getSelectedFile();
421
                                        if (!(file.getPath().endsWith(".gvl") || file.getPath().endsWith(".GVL"))){
422
                                                file=new File(file.getPath()+".gvl");
423
                                        }
424
                                        writeLegend(file);
425
                                }
426
            } else {}
427
        }
428
    }
429
    
430
    private void writeLegend(File file) {
431
                try {
432
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
433
                        Marshaller m = new Marshaller(writer);
434
                        m.setEncoding("ISO-8859-1");
435
                        m.marshal(renderer.getXMLEntity().getXmlTag());
436
                } catch (Exception e) {
437
                        NotificationManager.addError(PluginServices.getText(this, "Error_guardando_la_leyenda"), e);
438
                }
439
        }
440

    
441
        public void readLegend(File file) {
442
                try {
443
                        File xmlFile = new File(file.getAbsolutePath());
444
                        FileReader reader;
445
                        reader = new FileReader(xmlFile);
446

    
447
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
448
                        renderer = LegendFactory.createFromXML(new XMLEntity(tag));
449
                        //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
450
                } catch (FileNotFoundException e) {
451
                        NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
452
                } catch (MarshalException e) {
453
                        NotificationManager.addError(PluginServices.getText(this, "Al leer la leyenda"), e);
454
                } catch (ValidationException e) {
455
                        NotificationManager.addError(PluginServices.getText(this, "Al leer la leyenda"), e);
456
                } catch (XMLException e) {
457
                        NotificationManager.addError(PluginServices.getText(this, "Al leer la leyenda"), e);
458
                }
459
        }
460
    
461
        /* (non-Javadoc)
462
         * @see com.iver.andami.ui.mdiManager.View#getViewInfo()
463
         */
464
        public ViewInfo getViewInfo() {
465
                // Solo se llama una vez
466
                ViewInfo viewInfo = new ViewInfo(ViewInfo.MODELESSDIALOG);
467
                viewInfo.setWidth(650);
468
                viewInfo.setHeight(420);
469
                viewInfo.setTitle(PluginServices.getText(this,"propiedades_del_tema"));
470
                return viewInfo;
471
        }
472
        
473
        /**
474
         * @see com.iver.mdiApp.ui.MDIManager.View#viewActivated()
475
         */
476
        /*public void viewActivated() {
477
        }
478
        
479
        public FMap getMapContext() {
480
                return mapContext;
481
        }
482
        public FLayer getLayer() {
483
                return layer;
484
        }
485
        public Legend getRenderer() {
486
                return renderer;
487
        }*/
488
        
489
        /**
490
         * @return Returns the organizador.
491
         */
492
        public JTabbedPane getOrganizador() {
493
                return organizador;
494
        }
495
        /**
496
         * @param organizador The organizador to set.
497
         */
498
        public void setOrganizador(JTabbedPane organizador) {
499
                this.organizador = organizador;
500
        }
501
}