Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / table / gui / Table.java @ 7738

History | View | Annotate | Download (47.5 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.table.gui;
42

    
43
import java.awt.Color;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.event.KeyAdapter;
47
import java.awt.event.KeyEvent;
48
import java.awt.event.KeyListener;
49
import java.awt.event.MouseAdapter;
50
import java.awt.event.MouseEvent;
51
import java.beans.PropertyChangeEvent;
52
import java.beans.PropertyChangeListener;
53
import java.io.IOException;
54
import java.text.ParseException;
55
import java.util.BitSet;
56
import java.util.EventObject;
57

    
58
import javax.swing.BorderFactory;
59
import javax.swing.DefaultCellEditor;
60
import javax.swing.DefaultListSelectionModel;
61
import javax.swing.JComponent;
62
import javax.swing.JFrame;
63
import javax.swing.JLabel;
64
import javax.swing.JOptionPane;
65
import javax.swing.JPanel;
66
import javax.swing.JTextField;
67
import javax.swing.UIManager;
68
import javax.swing.border.Border;
69
import javax.swing.event.ListSelectionEvent;
70
import javax.swing.event.ListSelectionListener;
71
import javax.swing.table.AbstractTableModel;
72
import javax.swing.table.DefaultTableColumnModel;
73
import javax.swing.table.TableCellRenderer;
74
import javax.swing.table.TableColumn;
75

    
76
import org.apache.log4j.Logger;
77

    
78
import com.hardcode.driverManager.DriverLoadException;
79
import com.hardcode.gdbms.engine.data.driver.DriverException;
80
import com.hardcode.gdbms.engine.values.Value;
81
import com.hardcode.gdbms.engine.values.ValueFactory;
82
import com.iver.andami.PluginServices;
83
import com.iver.andami.messages.NotificationManager;
84
import com.iver.andami.ui.mdiFrame.MainFrame;
85
import com.iver.andami.ui.mdiManager.IWindowListener;
86
import com.iver.andami.ui.mdiManager.IWindowTransform;
87
import com.iver.andami.ui.mdiManager.SingletonWindow;
88
import com.iver.andami.ui.mdiManager.WindowInfo;
89
import com.iver.cit.gvsig.fmap.MapContext;
90
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
91
import com.iver.cit.gvsig.fmap.core.DefaultRow;
92
import com.iver.cit.gvsig.fmap.core.IFeature;
93
import com.iver.cit.gvsig.fmap.core.IGeometry;
94
import com.iver.cit.gvsig.fmap.core.IRow;
95
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
96
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
97
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
98
import com.iver.cit.gvsig.fmap.edition.AfterFieldEditEvent;
99
import com.iver.cit.gvsig.fmap.edition.AfterRowEditEvent;
100
import com.iver.cit.gvsig.fmap.edition.BeforeFieldEditEvent;
101
import com.iver.cit.gvsig.fmap.edition.BeforeRowEditEvent;
102
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
103
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
104
import com.iver.cit.gvsig.fmap.edition.EditionException;
105
import com.iver.cit.gvsig.fmap.edition.IEditableSource;
106
import com.iver.cit.gvsig.fmap.edition.IEditionListener;
107
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
108
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
109
import com.iver.cit.gvsig.fmap.edition.IWriteable;
110
import com.iver.cit.gvsig.fmap.edition.IWriter;
111
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
112
import com.iver.cit.gvsig.fmap.edition.commands.CommandListener;
113
import com.iver.cit.gvsig.fmap.layers.FLayer;
114
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
115
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
116
import com.iver.cit.gvsig.fmap.layers.SelectionEvent;
117
import com.iver.cit.gvsig.fmap.layers.SelectionListener;
118
import com.iver.cit.gvsig.gui.tables.Column;
119
import com.iver.cit.gvsig.project.documents.table.EditionTable;
120
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
121
import com.iver.utiles.swing.jtable.FieldSelectionEvent;
122
import com.iver.utiles.swing.jtable.FieldSelectionListener;
123
import com.iver.utiles.swing.jtable.SelectionHeaderSupport;
124

    
125
/**
126
 * DOCUMENT ME!
127
 *
128
 * @author Fernando Gonz?lez Cort?s
129
 */
130
public class Table extends JPanel implements SingletonWindow, EditionTable,
131
    IWindowListener,CommandListener, IWindowTransform, IEditionListener {
132
    private static Logger logger = Logger.getLogger(Table.class.getName());
133
    private javax.swing.JScrollPane jScrollPane = null;
134
    protected javax.swing.JTable table = null;
135
    protected ProjectTable model = null;
136
    protected JLabel jLabelStatus = null;
137
    protected MapContext fmap;
138
    protected boolean updating = false;
139
    private TableSelectionListener selectionListener = new TableSelectionListener();
140
    private long numReg = 0;
141
    protected SelectionHeaderSupport headerSelectionSupport = new SelectionHeaderSupport();
142
    private long[] orderIndexes = null;
143
    private long[] orderIndexesInverted = null;
144
    private IRow[] rowsCopied = null;
145
    private WindowInfo m_viewInfo = null;
146
        private boolean isPalette=false;
147
        private String[] antAliases;
148
        private int[] antMapping;
149
        /**
150
     * This is the default constructor
151
     */
152
    public Table() {
153
        super();
154
        initialize();
155
    }
156

    
157
    /**
158
     * DOCUMENT ME!
159
     *
160
     * @return DOCUMENT ME!
161
     */
162
    public ProjectTable getModel() {
163
        return model;
164
    }
165

    
166
    /**
167
     * DOCUMENT ME!
168
     *
169
     * @return DOCUMENT ME!
170
     */
171
    public BitSet getSelectedFieldIndices() {
172
            BitSet bs=headerSelectionSupport.getSelectedColumns();
173
//            BitSet newbs=new BitSet();
174
//            for (int i =1;i<bs.length();i++){
175
//                    if (bs.get(i))
176
//                            newbs.set(i-1);
177
//            }
178
//        return newbs;
179
            return bs;
180
    }
181

    
182
    /**
183
     * DOCUMENT ME!
184
     *
185
     * @return DOCUMENT ME!
186
     */
187
    public int[] getSelectedRowIndices() {
188
        return getTable().getSelectedRows();
189
    }
190

    
191
    /**
192
     * DOCUMENT ME!
193
     */
194
    protected void refreshControls() {
195
        try {
196
            MainFrame mF = PluginServices.getMainFrame();
197

    
198
            if (mF != null) {
199
                PluginServices.getMDIManager().getWindowInfo(Table.this).setTitle(PluginServices.getText(
200
                        this, "Tabla") + ": " + model.getName());
201
            }
202

    
203
            if (model.getAssociatedTable() != null) {
204
                this.fmap = ((FLayer) model.getAssociatedTable()).getMapContext();
205
            } else {
206
                this.fmap = null;
207
            }
208

    
209
            SelectableDataSource dataSource = (SelectableDataSource) model.getModelo()
210
                                                                          .getRecordset();
211
            dataSource.mapExternalFields();
212
            logger.debug("dataSource.start()");
213
            dataSource.start();
214

    
215
//            model.createAlias();
216

    
217
            ColumnModel cm=new ColumnModel(model);
218
//            cm.setDataModel(model);
219
            getTable().setColumnModel(cm);
220

    
221
            AbstractTableModel dataModel = new DataSourceDataModel(model);
222

    
223
            getModel().createAlias();
224

    
225
            getTable().setModel(dataModel);
226
//            TableColumn column = null;
227
//                        for (int i = 0; i < model.getColumnCount(); i++) {
228
//                            column = table.getColumnModel().getColumn(i);
229
//                            int w=model.getColumn(i).getWidth();
230
//                            column.setPreferredWidth(w); //sport column is bigger
231
//                            System.err.println("Table.Dentro de refreshControls. column=" + column.toString());
232
//
233
//                        }
234
//
235
//                TableColumn tc=getTable().getColumnModel().getColumn(0);
236
//                tc.setCellRenderer(new MyTableCellRenderer());
237

    
238

    
239
                        headerSelectionSupport.setTableHeader(getTable().getTableHeader());
240
            headerSelectionSupport.addFieldSelectionListener(new FieldSelectionListener() {
241
                    public void fieldSelected(FieldSelectionEvent e) {
242
                        if (PluginServices.getMainFrame() != null) {
243
                            PluginServices.getMainFrame().enableControls();
244
                        }
245
                    }
246
                });
247

    
248
            model.getModelo().getRecordset().addSelectionListener(selectionListener);
249

    
250
            updateSelection();
251
        } catch (DriverException e) {
252
            NotificationManager.addError("No se pudo leer la informaci?n", e);
253
        } catch (DriverLoadException e) {
254
            NotificationManager.addError("No se pudo leer la informaci?n", e);
255
        }
256
    }
257

    
258
    /**
259
     * DOCUMENT ME!
260
     *
261
     * @param table DOCUMENT ME!
262
     */
263
    public void setModel(ProjectTable table) {
264
        model = table;
265

    
266
        //Gesti?n del nombre de la ventana
267
        model.addPropertyChangeListener(new PropertyChangeListener() {
268
                public void propertyChange(PropertyChangeEvent evt) {
269
                    if (evt.getPropertyName().equals("name")) {
270
                        PluginServices.getMDIManager().getWindowInfo(Table.this)
271
                                      .setTitle(PluginServices.getText(this,
272
                                "Tabla") + ": " + (String) evt.getNewValue());
273
                    } else if (evt.getPropertyName().equals("model")) {
274
                        refreshControls();
275
                    }
276
                }
277
            });
278

    
279
        IEditableSource ies=getModel().getModelo();
280
        ies.addEditionListener(this);
281

    
282
        refreshControls();
283

    
284

    
285
    }
286
    class MyTableCellRenderer extends JLabel implements TableCellRenderer {
287
        final Border grayBorder = BorderFactory.createLineBorder(Color.darkGray);
288

    
289
        MyTableCellRenderer() {
290

    
291
        }
292

    
293
        public Component getTableCellRendererComponent(javax.swing.JTable table,
294
            Object value, boolean isSelected, boolean hasFocus, int row,
295
            int col) {
296
                JLabel label=new JLabel(String.valueOf(row+1));
297
                 label.setForeground(Color.blue);
298
                label.setOpaque(true);
299
                 if (isSelected)
300
                        label.setBackground(Color.yellow);
301
                else
302
                        label.setBackground(UIManager.getColor("Button.background"));
303

    
304
                label.setBorder(grayBorder);
305
                return label;
306
        }
307
      }
308

    
309
    /**
310
     *
311
     */
312
    public void updateSelection() {
313
        updating = true;
314
        try {
315
            DefaultListSelectionModel sm = (DefaultListSelectionModel) getTable()
316
                                                                           .getSelectionModel();
317
            sm.clearSelection();
318

    
319
            BitSet bs = (model.getModelo().getRecordset()).getSelection();
320
            sm.setValueIsAdjusting(true);
321

    
322
            if (orderIndexes != null) {
323
                for (int i = 0; i < orderIndexes.length; i++) {
324
                    if (bs.get(i)) {
325
                        sm.addSelectionInterval((int) orderIndexesInverted[i],
326
                            (int) orderIndexesInverted[i]);
327
                        if (isEditing())
328
                                table.setEditingRow((int)orderIndexesInverted[i]);
329
                    }
330
                }
331
            } else {
332
                for (int i = bs.nextSetBit(0); i >= 0;
333
                        i = bs.nextSetBit(i + 1)) {
334
                    sm.addSelectionInterval(i, i);
335
                    if (isEditing())
336
                            table.setEditingRow(i);
337
                }
338
            }
339

    
340
            sm.setValueIsAdjusting(false);
341
            try {
342
                numReg = model.getModelo().getRowCount();
343
            } catch (IOException e) {
344
                e.printStackTrace();
345
            }
346

    
347
            jLabelStatus.setText(" " +
348
                ((SelectableDataSource) model.getModelo().getRecordset()).getSelection()
349
                 .cardinality() + " / " + numReg + " " +
350
                PluginServices.getText(this, "registros_seleccionados_total") +
351
                ".");
352
            if (PluginServices.getMainFrame() != null)
353
                    PluginServices.getMainFrame().enableControls();
354
        } catch (DriverIOException e) {
355
            e.printStackTrace();
356
        } catch (DriverLoadException e) {
357
            e.printStackTrace();
358
        }
359
        updating = false;
360
    }
361

    
362
    /**
363
     * This method initializes this
364
     */
365
    protected void initialize() {
366
        jLabelStatus = new JLabel();
367
        setLayout(new java.awt.BorderLayout());
368
        jLabelStatus.setText("");
369
        jLabelStatus.setName("");
370
        jLabelStatus.setPreferredSize(new java.awt.Dimension(100, 18));
371
        add(getJScrollPane(), java.awt.BorderLayout.CENTER);
372
        this.add(jLabelStatus, java.awt.BorderLayout.SOUTH);
373
        this.setPreferredSize(new Dimension(300,200));
374
    }
375

    
376
    /**
377
     * This method initializes table
378
     *
379
     * @return javax.swing.JTable
380
     */
381
    public javax.swing.JTable getTable() {
382
        if (table == null) {
383
            table = new javax.swing.JTable();
384
            table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
385
            table.setSelectionModel(new DefaultListSelectionModel());
386
            table.getTableHeader().addMouseListener(new MouseHandler());
387
            table.addKeyListener(new TableKeyListener());
388
            table.addMouseListener(new MouseRow());
389
            table.setSelectionForeground(Color.blue);
390
                    table.setSelectionBackground(Color.yellow);
391
                    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
392
                    public void valueChanged(ListSelectionEvent e) {
393

    
394
                            if (updating) {
395
                                 return;
396
                        }
397

    
398
                        SelectableDataSource dataModel = null;
399

    
400
                        try {
401
                            dataModel = Table.this.model.getModelo()
402
                                                        .getRecordset();
403
                        } catch (DriverLoadException e1) {
404
                            e1.printStackTrace();
405
                        }
406

    
407
                        DefaultListSelectionModel model = (DefaultListSelectionModel) table.getSelectionModel();
408
                        BitSet selection = dataModel.getSelection();
409

    
410
                        for (int i = e.getFirstIndex(); i <= e.getLastIndex();
411
                                i++) {
412
                            if (orderIndexes != null) {
413
                                selection.set((int) orderIndexes[i],
414
                                    model.isSelectedIndex(i));
415
                            } else {
416
                                selection.set(i, model.isSelectedIndex(i));
417
                            }
418
                        }
419

    
420
                        if (e.getValueIsAdjusting() == false) {
421
                            if (fmap != null) {
422
                                fmap.endAtomicEvent();
423
                            }
424

    
425
                            dataModel.fireSelectionEvents();
426
                        } else {
427
                            if (fmap != null) {
428
                                fmap.beginAtomicEvent();
429
                            }
430
                        }
431

    
432
                        jLabelStatus.setText(" " + selection.cardinality() +
433
                            " / " + numReg + " " +
434
                            PluginServices.getText(this,
435
                                "registros_seleccionados_total") + ".");
436

    
437
                    }
438
                });
439

    
440
                       JTextField tf=new JTextField();
441
                    table.setDefaultEditor(Number.class, new DefaultEditor(tf));
442
            table.setDefaultEditor(String.class, new DefaultEditor(tf));
443
            table.setDefaultEditor(Object.class, new DefaultEditor(tf));
444
        }
445

    
446
        return table;
447
    }
448
    protected class DefaultEditor extends DefaultCellEditor {
449
                public Component getTableCellEditorComponent(javax.swing.JTable table,
450
                                Object value, boolean isSelected, int row, int column) {
451
                        JTextField tf=(JTextField)super.getTableCellEditorComponent(table, value, isSelected,
452
                                        row, column);
453
                        if (isSelected){
454
                                tf.setBackground(new Color(230,220,220));
455
                                tf.selectAll();
456

    
457
                        }
458
                        return tf;
459
                }
460

    
461
                public DefaultEditor(JTextField tf) {
462
                        super(tf);
463
                         //MouseListener[] mouseListeners=getTable().getEditorComponent().getMouseListeners();
464
                   // if (!mouseListeners[mouseListeners.length-1].getClass().equals(MouseRow.class)){
465
                   tf.addMouseListener(new MouseRow());
466
                   // }
467
                        getComponent().addKeyListener(new KeyAdapter() {
468
                                int keyPressed = 0;
469

    
470
                                public void keyPressed(KeyEvent ke) {
471
                                        if (ke.getKeyCode() != KeyEvent.VK_TAB)
472
                                                keyPressed++;
473
                                        JTextField tf = (JTextField) getComponent();
474

    
475

    
476
                                        if (ke.getKeyCode() == KeyEvent.VK_RIGHT
477
                                                        || ke.getKeyCode() == KeyEvent.VK_ENTER) {
478
                                                int caretPosition = tf.getCaretPosition();
479
                                                if (caretPosition >= tf.getText().length()) {
480
                                                        int x = table.getSelectedColumn();
481
                                                        int y = table.getSelectedRow();
482
                                                        if (x + 1 >= table.getColumnCount()) {
483
                                                                x = 0;
484
                                                                y++;
485
                                                        } else {
486
                                                                x++;
487
                                                        }
488
                                                        //table.changeSelection(y, x, false, true);
489
                                                        //initEditField(x,y);
490
                                                        getComponent().setEnabled(false);
491
                                                }
492

    
493
                                        } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
494
                                                int caretPosition = tf.getCaretPosition();
495
                                                if (caretPosition <= 0) {
496
                                                        int x = table.getSelectedColumn();
497
                                                        int y = table.getSelectedRow();
498
                                                        if (x == 0) {
499
                                                                x = table.getColumnCount() - 1;
500
                                                                if (y - 1 < 0)
501
                                                                        y = table.getRowCount() - 1;
502
                                                                else
503
                                                                        y--;
504
                                                        } else {
505
                                                                x--;
506
                                                        }
507
                                                        //table.changeSelection(y, x, false, true);
508
                                                        //initEditField(x,y);
509
                                                        getComponent().setEnabled(false);
510
                                                }
511

    
512
                                        }
513
                                }
514

    
515
                                public void keyReleased(KeyEvent ke) {
516
                                        JComponent editor = (JComponent) DefaultEditor.this
517
                                                        .getComponent();
518
                                        if (editor instanceof JTextField) {
519
                                                if (keyPressed == 0) {
520
                                                        ((JTextField) editor).setText(String.valueOf(ke
521
                                                                        .getKeyChar()));
522
                                                }
523
                                        }
524
                                        keyPressed--;
525
                                        if (keyPressed < 0)
526
                                                keyPressed = 0;
527
                                        getComponent().setEnabled(true);
528
                                }
529
                        });
530

    
531
                }
532

    
533
                public Object getCellEditorValue() {
534
                        String s = ((JTextField) (DefaultEditor.this.getComponent()))
535
                                        .getText();
536
                        getComponent().setEnabled(true);
537
                        return s;
538
                }
539

    
540
                public boolean isCellEditable(EventObject event) {
541
                        // IF NUMBER OF CLICKS IS LESS THAN THE CLICKCOUNTTOSTART RETURN
542
                        // FALSE
543
                        // FOR CELL EDITING.
544
                        if (event instanceof MouseEvent) {
545
                                return ((MouseEvent) event).getClickCount() >= getClickCountToStart();
546
                        }
547

    
548
                        return true;
549
                }
550
        }
551

    
552

    
553

    
554

    
555
    /**
556
         * This method initializes jScrollPane
557
         *
558
         * @return javax.swing.JScrollPane
559
         */
560
    protected javax.swing.JScrollPane getJScrollPane() {
561
        if (jScrollPane == null) {
562
            jScrollPane = new javax.swing.JScrollPane();
563
            jScrollPane.setViewportView(getTable());
564
        }
565

    
566
        return jScrollPane;
567
    }
568

    
569
    /**
570
         * @see com.iver.mdiApp.ui.MDIManager.SingletonWindow#getWindowModel()
571
         */
572
    public Object getWindowModel() {
573
        return model;
574
    }
575

    
576
    /**
577
         * This method is used to get <strong>an initial</strong> ViewInfo object
578
         * for this Table. It is not intended to retrieve the ViewInfo object in a
579
         * later time. <strong>Use PluginServices.getMDIManager().getViewInfo(view)
580
         * to retrieve the ViewInfo object at any time after the creation of the
581
         * object.
582
         *
583
         * @see com.iver.mdiApp.ui.MDIManager.IWindow#getWindowInfo()
584
         */
585
    public WindowInfo getWindowInfo() {
586
            if (m_viewInfo==null) {
587
                    m_viewInfo = new WindowInfo(WindowInfo.ICONIFIABLE |
588
                        WindowInfo.MAXIMIZABLE | WindowInfo.RESIZABLE);
589
                    m_viewInfo.setTitle(PluginServices.getText(this, "Tabla")+ " : " +model.getName());
590
                    m_viewInfo.setWidth(300);
591
                    m_viewInfo.setHeight(200);
592
            }
593
        return m_viewInfo;
594
    }
595

    
596
    /**
597
     * DOCUMENT ME!
598
     *
599
     * @param indexes
600
     *
601
     * @throws IOException
602
     */
603
    public void setOrder(long[] indexes) throws IOException {
604
        orderIndexes = indexes;
605
        orderIndexesInverted = new long[orderIndexes.length];
606

    
607
        for (int i = 0; i < indexes.length; i++) {
608
            orderIndexesInverted[(int) indexes[i]] = i;
609
        }
610

    
611
        updating = true;
612
        ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
613
        updating = false;
614

    
615
        updateSelection();
616
    }
617

    
618
    /*  public void startEditing() throws DriverException{
619
       // dw = model.getModelo().getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
620
       // dw.beginTrans();
621
       }
622
     */
623

    
624
    /**
625
     * DOCUMENT ME!
626
     */
627

    
628
    /*  public void cancelEditing() throws DriverException {
629
       dw.rollBackTrans();
630
       dw = null;
631
       }
632
     */
633

    
634
    /**
635
     * DOCUMENT ME!
636
     */
637

    
638
    /*  public void stopEditing() throws DriverException {
639
       // dw.commitTrans();
640
       // dw = null;
641
       // model.getModelo().stop();
642
       // model.getModelo().start();
643
       }
644
     */
645

    
646
    /**
647
     * DOCUMENT ME!
648
     */
649

    
650
    /*  public boolean isEditing() {
651
       return dw != null;
652
       }
653
     */
654

    
655
    /**
656
     * Quita los campos seleccionados
657
     */
658
    public void clearSelectedFields() {
659
        headerSelectionSupport.clearSelectedColumns();
660
    }
661

    
662
    /**
663
     * DOCUMENT ME!
664
     *
665
     * @param index DOCUMENT ME!
666
     *
667
     * @return DOCUMENT ME!
668
     */
669
    public Value[] getValueRow(int index) {
670
        DataSourceDataModel dsdm = (DataSourceDataModel) getTable().getModel();
671
        Value[] values = new Value[dsdm.getColumnCount()];
672

    
673
        for (int i = 0; i < dsdm.getColumnCount(); i++) {
674
            values[i] = (Value) dsdm.getValueAt(index, i);
675
        }
676

    
677
        return values;
678
    }
679

    
680
    /* private void refresh() throws DriverException{
681
       //dw.commitTrans();
682
       //model.getModelo().stop();
683
       //dw.beginTrans();
684
           //DataSourceDataModel dsdm=(DataSourceDataModel)getTable().getModel();
685
           //dsdm.fireTableDataChanged();
686
       }*/
687
    /*  public void addEmptyRow() throws DriverException{
688
       ValueCollection valuePK=new ValueCollection();
689
           valuePK.setValues(new Value[]{ValueFactory.createValue(dw.getRowCount())});
690
           dw.insertEmptyRow(valuePK);
691
           refresh();
692
       }
693
     */
694
    /*        public void copySelectedRows() throws DriverException{
695
       int[] sel=getSelectedRowIndices();
696
       for(int i=0;i<sel.length;i++){
697
               rowsCopied.add(getValueRow(sel[i]));
698
       }
699
       }
700
     */
701
    /*        public void addSelectionToEnd() throws DriverException {
702
       for (int i=0;i<rowsCopied.size();i++){
703
               dw.insertFilledRow((Value[])rowsCopied.get(i));
704
       }
705
       refresh();
706
       }
707
     */
708
    /*public void delSelectionRow() throws DriverException{
709
       int[] sel=getSelectedRowIndices();
710
       for(int i=sel.length-1;i>=0;i--){
711
               dw.deleteRow(sel[i]);
712
       }
713
       refresh();
714
       }
715
     */
716
    /*public boolean isCopy(){
717
       return !rowsCopied.isEmpty();
718
       }
719
     */
720
    /*
721
       public void addSelectionToRow() throws DriverException {
722
                   int[] sel=getSelectedRowIndices();
723
                           dw.insertFilledRow((Value[])rowsCopied.get(i),sel[0]);
724
                   refresh();
725
           }
726
     */
727
    public void startEditing() throws EditionException {
728
       getModel().getModelo().startEdition(EditionEvent.ALPHANUMERIC);
729
       // Guardamos el estado actual para recuperarlo si cancelamos la edici?n.
730
       antAliases = getModel().getAliases();
731
       antMapping = getModel().getMapping();
732
       //int row=table.getSelectedRow();
733
       //int column=table.getSelectedColumn();
734
       //if (row!=-1 && column!=-1)
735
       //   initEditField(column,row);
736

    
737
//       View[] views = (View[]) PluginServices.getMDIManager().getAllViews();
738
//
739
//                for (int i=0 ; i<views.length ; i++){
740
//                        if (views[i] instanceof com.iver.cit.gvsig.gui.View){
741
//                                com.iver.cit.gvsig.gui.View view=(com.iver.cit.gvsig.gui.View)views[i];
742
//                                FLayers layers =view.getMapControl().getMapContext().getLayers();
743
//                                for (int j=0;j<layers.getLayersCount();j++){
744
//                                        if (layers.getLayer(j).equals(this.getModel().getAssociatedTable())){
745
//                                                view.showConsole();
746
//                                                ((FLyrVect)layers.getLayer(j)).setActive(true);
747
//                                                ((FLyrVect)layers.getLayer(j)).setEditing(true);
748
//                                        }
749
//                                }
750
//                        }
751
//                }
752
    }
753
    private void initEditField(int[] x,int[] y){
754
            if (getTable().getRowCount()>0){
755
            if (isEditing()) {
756

    
757
                        if (x.length == 1 && y.length == 1)
758
                                table.editCellAt(y[0], x[0]);
759
                        JTextField tf = (JTextField) table.getEditorComponent();
760
                        if (tf != null) {
761
                                tf.selectAll();
762
                                tf.requestFocus();
763
                        }
764
//                        if (y.length > 0 && x.length > 0) {
765
//                                getTable().setRowSelectionInterval(y[0], y[y.length - 1]);
766
//                                getTable().setColumnSelectionInterval(x[0], x[x.length - 1]);
767
//                        }
768

    
769
                }
770
            }
771
    }
772
    /**
773
         * DOCUMENT ME!
774
         */
775
    public void stopEditing() {
776
        try {
777
                this.stopEditingCell();
778

    
779
            FLyrVect lyr = (FLyrVect) getModel().getAssociatedTable();
780

    
781
            if ((lyr != null) &&
782
                    lyr.getSource() instanceof VectorialEditableAdapter) {
783
                    VectorialEditableAdapter vea = (VectorialEditableAdapter) lyr.getSource();
784
                    ISpatialWriter spatialWriter = (ISpatialWriter) vea.getOriginalDriver();
785
                    vea.stopEdition(spatialWriter,EditionEvent.ALPHANUMERIC);
786
                    lyr.setSource(vea.getOriginalAdapter());
787
                    lyr.setEditing(false);
788
                    refreshControls();
789

    
790
            } else {
791

    
792
                 IEditableSource ies=getModel().getModelo();
793
                 if (ies instanceof IWriteable)
794
                 {
795
                         IWriteable w = (IWriteable) ies;
796
                         IWriter writer = w.getWriter();
797
                         if (writer == null)
798
                         {
799
                                 NotificationManager.addError("No existe driver de escritura para la tabla"
800
                                                 + getModel().getName(), new EditionException());
801
                         }
802
                         else
803
                         {
804
                                             ITableDefinition tableDef = ies.getTableDefinition();
805
                                            writer.initialize(tableDef);
806

    
807
                                 ies.stopEdition(writer,EditionEvent.ALPHANUMERIC);
808

    
809
                                 // TODO: RELOAD
810
//                                 EditableAdapter edAdapter = (EditableAdapter) ies;
811
//                                 // Restaura el datasource a su estado original
812
//                                 edAdapter.setOriginalDataSource(edAdapter.getRecordset());
813
                                 ies.getSelection().clear();
814
                                 refreshControls();
815
                         }
816
                 }
817

    
818
                 /*
819
                GdbmsWriter gdbmswriter = new GdbmsWriter();
820
                gdbmswriter.setDataWare(getModel().getModelo()
821
                                                              .getRecordset()
822
                                                              .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER));
823
                gdbmswriter.preProcess();
824

825
                for (int i = 0; i < getModel().getModelo().getRowCount();
826
                        i++) {
827
                    gdbmswriter.process(getModel().getModelo().getRow(i));
828
                }
829

830
                gdbmswriter.postProcess();
831
                */
832

    
833
            }
834

    
835
        } catch (Exception e) {
836
            NotificationManager.addError("No se pudo guardar la edici?n", e);
837
        }
838
    }
839

    
840
    /**
841
     * DOCUMENT ME!
842
     *
843
     * @param index DOCUMENT ME!
844
     */
845
    public void hideColumns(int[] index) {
846
        // TODO Auto-generated method stub
847
    }
848

    
849
    /**
850
     * DOCUMENT ME!
851
     *
852
     * @param index DOCUMENT ME!
853
     */
854
    public void setUneditableColumns(int[] index) {
855
        // TODO Auto-generated method stub
856
    }
857

    
858
    /**
859
     * DOCUMENT ME!
860
     *
861
     * @param numColumns DOCUMENT ME!
862
     * @param values DOCUMENT ME!
863
     */
864
    public void setDefaultValues(int[] numColumns, Value[] values) {
865
        // TODO Auto-generated method stub
866
    }
867

    
868
    /**
869
     * DOCUMENT ME!
870
     *
871
     * @return DOCUMENT ME!
872
     */
873
    public Value getDefaultValue() {
874
        // TODO Auto-generated method stub
875
        return null;
876
    }
877

    
878
    /**
879
     * DOCUMENT ME!
880
     *
881
     * @throws IOException DOCUMENT ME!
882
     */
883
    public void cancelEditing() throws IOException {
884
            this.cancelEditingCell();
885
        getModel().getModelo().cancelEdition(EditionEvent.ALPHANUMERIC);
886
        if (antAliases != null)
887
        {
888
                getModel().setAliases(antAliases);
889
                getModel().setMapping(antMapping);
890
                getModel().recalculateColumnsFromAliases();
891
        }
892
        else
893
        {
894
                System.err.println("Algo ha ido mal con antAliases");
895
        }
896
        //refresh();
897
        refreshControls();
898
    }
899

    
900
    /**
901
     * DOCUMENT ME!
902
     *
903
     * @return DOCUMENT ME!
904
     */
905
    public boolean isEditing() {
906
        return getModel().getModelo().isEditing();
907
    }
908

    
909
    /**
910
     * DOCUMENT ME!
911
     */
912
    public void refresh() {
913
            int row=table.getSelectedRow();
914
            int column=table.getSelectedColumn();
915
            if (row!=-1 && column!=-1 && table.getEditorComponent()!=null){
916
                    Value[] values=getValueRow(row);
917
                    JTextField jtf=(JTextField)table.getEditorComponent();
918
                    jtf.setText(values[column].toString());
919
            }
920
        updating = true;
921
        ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
922

    
923
        updating = false;
924
        updateSelection();
925
        PluginServices.getMainFrame().enableControls();
926

    
927
    }
928

    
929
    /**
930
     * Add the rows that are passed like parameter and if parameter is null a
931
     * row is added empties.
932
     *
933
     * @param rows Rows to add or null.
934
     *
935
     * @throws DriverIOException
936
     * @throws IOException
937
     */
938
    public void addRow(IRow[] rows) throws DriverIOException, IOException {
939
            IEditableSource ies=getModel().getModelo();
940
            try {
941
            if (rows == null) {
942

    
943
                    if (getModel().getAssociatedTable()!=null){
944
                            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),"No se puede a?adir una fila a una tabla asociada a una capa.");
945
                            return;
946
                    }
947
                IRow row;
948
                int numAttr=getModel().getModelo()
949
                        .getRecordset()
950
                        .getFieldCount();
951
                    Value[] values=new Value[numAttr];
952
                    for (int i=0;i<numAttr;i++){
953
                            values[i]=ValueFactory.createNullValue();
954
                    }
955
                row = new DefaultRow(values);
956
                ies.addRow(row,"Fila en blanco",EditionEvent.ALPHANUMERIC);
957
            } else {
958
                    ies.startComplexRow();
959
                for (int i = 0; i < rows.length; i++) {
960
                   ies.addRow(((IRowEdited) rows[i]).getLinkedRow(),"Pegar filas",EditionEvent.ALPHANUMERIC);
961
                }
962
                String description=PluginServices.getText(this,"add_rows");
963
                ies.endComplexRow(description);
964
            }
965
        } catch (DriverException e) {
966
            // TODO Auto-generated catch block
967
            e.printStackTrace();
968
        } catch (DriverLoadException e) {
969
            // TODO Auto-generated catch block
970
            e.printStackTrace();
971
        }
972

    
973
        refresh();
974

    
975
    }
976

    
977
    /**
978
     * Copy in the arraylist the rows that be selected just then.
979
     *
980
     * @throws DriverIOException
981
     * @throws IOException
982
     */
983
    public void copyRow() throws DriverIOException, IOException {
984
        int[] index = getSelectedRowIndices();
985
        rowsCopied = new IRow[index.length];
986

    
987
        for (int i = 0; i < index.length; i++) {
988
            rowsCopied[i] = getModel().getModelo().getRow(index[i]);
989
        }
990
    }
991

    
992
    /**
993
     * Cut the rows that be selected just then.
994
     *
995
     * @throws DriverIOException
996
     * @throws IOException
997
     */
998
    public void cutRow() throws DriverIOException, IOException {
999
        int[] index = getSelectedRowIndices();
1000
        rowsCopied = new IRow[index.length];
1001

    
1002
        for (int i = 0; i < index.length; i++) {
1003
            rowsCopied[i] = getModel().getModelo().getRow(index[i]);
1004
        }
1005

    
1006
        removeRow();
1007
    }
1008

    
1009
    /**
1010
     * Remove in the rows that be selected just then.
1011
     *
1012
     * @throws DriverIOException
1013
     * @throws IOException
1014
     */
1015
    public void removeRow() throws DriverIOException, IOException {
1016
            int[] index = getSelectedRowIndices();
1017
        getModel().getModelo().startComplexRow();
1018
        for (int i = index.length-1; i >=0; i--) {
1019
            getModel().getModelo().removeRow(index[i],"Eliminar fila", EditionEvent.ALPHANUMERIC);
1020
        }
1021
//        int[] sel={0};
1022
//        getTable().setEditingRow(-1);
1023
//        getTable().getCellEditor().
1024
//        initEditField(sel,sel);
1025
        if (getTable().getCellEditor() != null)
1026
                getTable().getCellEditor().cancelCellEditing();
1027
        String description=PluginServices.getText(this,"remove_rows");
1028
        getModel().getModelo().endComplexRow(description);
1029
        getTable().clearSelection();
1030

    
1031
        refresh();
1032
        //repaintAssociatedView();
1033
    }
1034

    
1035
//    private void repaintAssociatedView(){
1036
//             View[] views = (View[]) PluginServices.getMDIManager().getAllViews();
1037
//
1038
//                 for (int i=0 ; i<views.length ; i++){
1039
//                         if (views[i] instanceof com.iver.cit.gvsig.gui.View){
1040
//                                 com.iver.cit.gvsig.gui.View view=(com.iver.cit.gvsig.gui.View)views[i];
1041
//                                 FLayers layers =view.getMapControl().getMapContext().getLayers();
1042
//                                 for (int j=0;j<layers.getLayersCount();j++){
1043
//                                         if (layers.getLayer(j).equals(this.getModel().getAssociatedTable())){
1044
//                                                 view.getMapControl().getMapContext().invalidate();
1045
//                                         }
1046
//                                 }
1047
//                         }
1048
//                 }
1049
//    }
1050
    /**
1051
     * DOCUMENT ME!
1052
     */
1053
    public void addColumn(FieldDescription newField) {
1054
            EditableAdapter edAdapter = (EditableAdapter) getModel().getModelo();
1055
            try {
1056
                        edAdapter.addField(newField);
1057
                        if (getTable().getCellEditor() != null)
1058
                                getTable().getCellEditor().cancelCellEditing();
1059
                getModel().setModel(edAdapter); // Para que se recalculen los campos. TODO: Limpiear todo esto
1060
                // refresh();
1061
                refreshControls();
1062
                } catch (EditionException e) {
1063
                        e.printStackTrace();
1064
                        NotificationManager.addError(e);
1065
                }
1066

    
1067
    }
1068

    
1069
    /**
1070
     * DOCUMENT ME!
1071
     */
1072
    public void removeColumn() {
1073
            EditableAdapter edAdapter = (EditableAdapter) getModel().getModelo();
1074
            try {
1075
                    BitSet selectedFields = getSelectedFieldIndices();
1076
                    SelectableDataSource sds = edAdapter.getRecordset();
1077
                    edAdapter.startComplexRow();
1078
                    FieldDescription[] auxFlds = sds.getFieldsDescription();
1079
                    for(int i=selectedFields.nextSetBit(0); i>=0; i=selectedFields.nextSetBit(i+1)) {
1080
                            FieldDescription fld = auxFlds[i];
1081
                            edAdapter.removeField(fld.getFieldAlias());
1082
                    }
1083
                    if (getTable().getCellEditor() != null)
1084
                                getTable().getCellEditor().cancelCellEditing();
1085

    
1086
                edAdapter.endComplexRow(PluginServices.getText(this, "remove_fields"));
1087
                clearSelectedFields();
1088
                getModel().setModel(edAdapter); // Para que se recalculen los campos. TODO: Limpiear todo esto
1089
                // refresh();
1090
                refreshControls();
1091
                } catch (EditionException e) {
1092
                        e.printStackTrace();
1093
                        NotificationManager.addError(e);
1094
                } catch (DriverException e) {
1095
                        e.printStackTrace();
1096
                        NotificationManager.addError(e);
1097
                } catch (IOException e) {
1098
                        e.printStackTrace();
1099
                        NotificationManager.addError(e);
1100
                } catch (DriverIOException e) {
1101
                        e.printStackTrace();
1102
                        NotificationManager.addError(e);
1103
                }
1104

    
1105
    }
1106

    
1107
    /**
1108
     * Return if we have rows copied or not.
1109
     *
1110
     * @return True if we have rows copied.
1111
     */
1112
    public boolean isCopied() {
1113
        return (rowsCopied != null);
1114
    }
1115

    
1116
    /**
1117
     * Paste the arraylist rows.
1118
     *
1119
     * @throws DriverIOException
1120
     * @throws IOException
1121
     */
1122
    public void pasteRow() throws DriverIOException, IOException {
1123
        addRow(rowsCopied);
1124
        //repaintAssociatedView();
1125
    }
1126

    
1127
    /**
1128
     * DOCUMENT ME!
1129
     */
1130
    public void windowActivated() {
1131
        //if (isEditing() && getModel().getModelo() instanceof VectorialEditableAdapter)
1132
        updateSelection();
1133
    }
1134

    
1135
    /**
1136
     * DOCUMENT ME!
1137
     */
1138
    public void windowClosed() {
1139
        // TODO Auto-generated method stub
1140
    }
1141

    
1142
    /**
1143
     * DOCUMENT ME!
1144
     *
1145
     * @author Fernando Gonz?lez Cort?s
1146
     */
1147
    public class DataSourceDataModel extends AbstractTableModel {
1148
        //private SelectableDataSource dataSource;
1149
        ProjectTable pt;
1150

    
1151
        /**
1152
         * Crea un nuevo DataSourceDataModel.
1153
         *
1154
         * @param pt DOCUMENT ME!
1155
         */
1156
        public DataSourceDataModel(ProjectTable pt) {
1157
            this.pt = pt;
1158

    
1159
            //try {
1160
            //dataSource = pt.getModelo().getRecordset();
1161
            //} catch (DriverLoadException e) {
1162
            // TODO Auto-generated catch block
1163
            //        e.printStackTrace();
1164
            //}
1165
        }
1166

    
1167
        /**
1168
         * Returns the name of the field.
1169
         *
1170
         * @param col index of field
1171
         *
1172
         * @return Name of field
1173
         */
1174
        public String getColumnName(int col) {
1175
//                if (col==0)
1176
//                        return " ";
1177
//                col--;
1178
                return pt.getAliases()[col];
1179
//                int i=pt.getMapping()[col];
1180
//                return pt.getAliases()[i];
1181
        }
1182

    
1183
        /**
1184
         * Returns the number of fields.
1185
         *
1186
         * @return number of fields
1187
         */
1188
        public int getColumnCount() {
1189
            return pt.getColumnCount();
1190
        }
1191

    
1192
        /**
1193
         * Returns number of rows.
1194
         *
1195
         * @return number of rows.
1196
         */
1197
        public int getRowCount() {
1198
            try {
1199
                    IEditableSource des = pt.getModelo();
1200
                return (int) des.getRowCount();
1201
            } catch (DriverIOException e) {
1202
                return 0;
1203
            } catch (IOException e) {
1204
                return 0;
1205
            }
1206
        }
1207

    
1208
        /**
1209
         * DOCUMENT ME!
1210
         *
1211
         * @param row DOCUMENT ME!
1212
         * @param col DOCUMENT ME!
1213
         *
1214
         * @return DOCUMENT ME!
1215
         */
1216
        public Object getValueAt(int row, int col) {
1217

    
1218
//           if (col==0){
1219
//                   return new Integer(row);
1220
//           }
1221
//           col--;
1222
           int numRow;
1223
           if (orderIndexes != null && row < orderIndexes.length) {
1224
                   numRow=(int)orderIndexes[row];
1225
           }else {
1226
                   numRow=row;
1227
           }
1228
                try {
1229
                        IEditableSource des = pt.getModelo();
1230
                        Object obj =null;
1231
                                IRowEdited rowEdited=des.getRow(numRow);
1232
                                obj= rowEdited.getAttribute(pt.getMapping()[col]);
1233
                                        return obj;
1234
                        } catch (DriverIOException e1) {
1235
                                e1.printStackTrace();
1236
                                return ValueFactory.createValue("").toString();
1237
                        } catch (IOException e1) {
1238
                                e1.printStackTrace();
1239
                                return ValueFactory.createValue("").toString();
1240
                        }
1241
            }
1242

    
1243
        /**
1244
         * DOCUMENT ME!
1245
         *
1246
         * @param rowIndex DOCUMENT ME!
1247
         * @param columnIndex DOCUMENT ME!
1248
         *
1249
         * @return DOCUMENT ME!
1250
         */
1251
        public boolean isCellEditable(int rowIndex, int columnIndex) {
1252
//                if (columnIndex==0)
1253
//                return false;
1254

    
1255
                return isEditing();
1256
        }
1257

    
1258
        /**
1259
         * DOCUMENT ME!
1260
         *
1261
         * @param aValue DOCUMENT ME!
1262
         * @param rowIndex DOCUMENT ME!
1263
         * @param columnIndex DOCUMENT ME!
1264
         *
1265
         * @throws RuntimeException DOCUMENT ME!
1266
         */
1267
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
1268
//                 if (columnIndex==0)
1269
//                 throw new UnsupportedOperationException("Row Number is a read-only column");
1270
//                 columnIndex--;
1271
                Value v;
1272
                 int numRow;
1273
             if (orderIndexes != null) {
1274
                     numRow=(int)orderIndexes[rowIndex];
1275
             }else {
1276
                     numRow=rowIndex;
1277
             }
1278
                if (getValueAt(rowIndex,columnIndex)==null || getValueAt(rowIndex,columnIndex).toString().equals(aValue))
1279
                    return;
1280
            try {
1281
                    IEditableSource des = pt.getModelo();
1282
                    v = ValueFactory.createValueByType(aValue.toString(),
1283
                        des.getRecordset().getFieldType(columnIndex));
1284
                IRowEdited row = des.getRow(numRow); //.getAttribute(columnIndex);
1285
                Value[] values = row.getAttributes();
1286
                values[columnIndex] = v;
1287

    
1288
                IRow newRow = null;
1289

    
1290
                if (row.getLinkedRow() instanceof IFeature) {
1291
                    IGeometry geometry = ((DefaultFeature) row.getLinkedRow()).getGeometry();
1292
                    newRow = new DefaultFeature(geometry, values,row.getID());
1293
                } else {
1294
                    newRow = new DefaultRow(values,row.getID());
1295
                }
1296

    
1297
                des.modifyRow(numRow, newRow,"Editar valor", EditionEvent.ALPHANUMERIC);
1298
            } catch (DriverException e1) {
1299
                throw new RuntimeException(e1);
1300
            } catch (ParseException e) {
1301
                    JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),"formato_del_campo_incorrecto");
1302
                        return;
1303
            } catch (DriverLoadException e) {
1304
                throw new RuntimeException(e);
1305
            } catch (DriverIOException e) {
1306
                throw new RuntimeException(e);
1307
            } catch (IOException e) {
1308
                throw new RuntimeException(e);
1309
            } catch (NumberFormatException e) {
1310
                        /*        NotificationManager.addError(PluginServices.-getText(this,"numero_incorrecto")+
1311
                                                "\n"+PluginServices.-getText(this,"fila")+" = "+rowIndex+
1312
                                                "\n"+PluginServices.-getText(this,"columna")+ " = "+columnIndex,e);
1313
                        */
1314
                        }
1315
        }
1316
    }
1317
    public class ColumnModel extends DefaultTableColumnModel{
1318
            private ProjectTable pt;
1319
                public ColumnModel(ProjectTable pt) {
1320
                        this.pt = pt;
1321
                }
1322

    
1323

    
1324
                public int getTotalColumnWidth() {
1325
//                        int w=0;
1326
//                        for (int i=0;i<getColumnCount();i++){
1327
//                                w+=pt.getColumn(i).getWidth();
1328
//                        }
1329
                        return super.getTotalColumnWidth();
1330
                }
1331

    
1332
                public void moveColumn(int columnIndex, int newIndex) {
1333
                        String[] aliases = getModel().getAliases();
1334
                        if (columnIndex != newIndex) {
1335
                                String aux = aliases[getModel().getMapping()[columnIndex]];
1336
                                aliases[getModel().getMapping()[columnIndex]] = aliases[getModel().getMapping()[newIndex]];
1337
                                aliases[getModel().getMapping()[newIndex]] = aux;
1338
                                /*int[] mapping = getModel().getMapping();
1339
                                int mappedColumnIndex = mapping[columnIndex];
1340
                                int mappedNewIndex = mapping[newIndex];
1341
                                mapping[columnIndex] = mappedNewIndex;
1342
                                mapping[newIndex] = mappedColumnIndex;
1343
                                String aux = aliases[mappedColumnIndex];
1344
                                aliases[mappedColumnIndex] = aliases[mappedNewIndex];
1345
                                aliases[mappedNewIndex] = aux;
1346
                                */
1347
                        }
1348
                        super.moveColumn(columnIndex, newIndex);
1349

    
1350
                }
1351

    
1352

    
1353
                public void propertyChange(PropertyChangeEvent arg0) {
1354
                        try{
1355
                        super.propertyChange(arg0);
1356
                        int w=((Integer)arg0.getNewValue()).intValue();
1357
                        if (arg0.getSource() instanceof TableColumn && (w!=75)){
1358
                                TableColumn tc=(TableColumn)arg0.getSource();
1359
                                Column column=pt.getColumn(tc.getModelIndex());
1360
                                column.setWidth(w);
1361
                                System.out.println("Index guardar = "+tc.getModelIndex()+" , "+"Anchura = "+w);
1362
                        }
1363
                        }catch (Exception e) {
1364
                                System.out.println("PETA");
1365
                        }
1366

    
1367
                }
1368
        }
1369
    /**
1370
     * DOCUMENT ME!
1371
     *
1372
     * @author Vicente Caballero Navarro
1373
     */
1374
    public class TableSelectionListener implements SelectionListener {
1375
        /**
1376
         * @see com.iver.cit.gvsig.fmap.layers.LegendListener#selectionChanged(com.iver.cit.gvsig.fmap.layers.LayerEvent)
1377
         */
1378
        public void selectionChanged(SelectionEvent e) {
1379
            updateSelection();
1380
            Table.this.repaint();
1381
        }
1382
    }
1383

    
1384
    /**
1385
     * DOCUMENT ME!
1386
     *
1387
     * @author Vicente Caballero Navarro
1388
     */
1389
    private class MouseHandler extends MouseAdapter {
1390
        /**
1391
         * DOCUMENT ME!
1392
         *
1393
         * @param e DOCUMENT ME!
1394
         */
1395
        public void mouseClicked(MouseEvent e) {
1396

    
1397
            /* JTableHeader h = (JTableHeader) e.getSource();
1398
               TableColumnModel columnModel = h.getColumnModel();
1399
               int viewColumn = columnModel.getColumnIndexAtX(e.getX());
1400
               int column = columnModel.getColumn(viewColumn).getModelIndex();
1401
               if (column != -1) {
1402
               }*/
1403
        }
1404
    }
1405
    /**
1406
     * DOCUMENT ME!
1407
     *
1408
     * @author Vicente Caballero Navarro
1409
     */
1410
    private class TableKeyListener implements KeyListener {
1411

    
1412
                public void keyPressed(KeyEvent arg0) {
1413
                        //JTextField tf=(JTextField)table.getEditorComponent();
1414
                        //table.setCellSelectionEnabled(true);
1415
                        //FocusManager fm = FocusManager.getCurrentManager();
1416
                        //fm.focusPreviousComponent(table);
1417
                }
1418

    
1419
                public void keyReleased(KeyEvent ke) {
1420
                        int[] row=table.getSelectedRows();
1421
                    int[] column=table.getSelectedColumns();
1422
                    initEditField(column,row);
1423
                }
1424

    
1425
                public void keyTyped(KeyEvent arg0) {
1426
                        // TODO Auto-generated method stub
1427

    
1428
                }
1429

    
1430
    }
1431

    
1432
    /**
1433
     * DOCUMENT ME!
1434
     *
1435
     * @author Vicente Caballero Navarro
1436
     */
1437
    private class MouseRow extends MouseAdapter {
1438
               public void mouseReleased(MouseEvent arg0) {
1439
                        super.mouseReleased(arg0);
1440
                        int[] row=table.getSelectedRows();
1441
                    int[] column=table.getSelectedColumns();
1442
                    initEditField(column,row);
1443
                }
1444

    
1445
                /**
1446
         * DOCUMENT ME!
1447
         *
1448
         * @param e DOCUMENT ME!
1449
         */
1450
    /*    public void mouseClicked(MouseEvent e) {
1451
            super.mouseClicked(e);
1452

1453

1454
                PluginServices.getMainFrame().enableControls();
1455

1456
            if (e.getButton() == MouseEvent.BUTTON3) {
1457
                new PopupMenu(e.getPoint());
1458
            }
1459
        }
1460
*/
1461
    }
1462

    
1463
        public void commandRepaint() {
1464
                refresh();
1465
        }
1466

    
1467
        public void commandRefresh() {
1468
                commandRepaint();
1469
        }
1470

    
1471
        public void toPalette() {
1472
                isPalette=true;
1473
                m_viewInfo.toPalette(true);
1474
                m_viewInfo.setClosed(false);
1475
                PluginServices.getMDIManager().changeWindowInfo(this,getWindowInfo());
1476
        }
1477

    
1478
        public void restore() {
1479
                isPalette=false;
1480
                m_viewInfo.toPalette(false);
1481
                m_viewInfo.setClosed(false);
1482
                PluginServices.getMDIManager().changeWindowInfo(this,getWindowInfo());
1483
        }
1484

    
1485
        public boolean isPalette() {
1486
                return isPalette;
1487
        }
1488

    
1489

    
1490
        private void addNumbers(){
1491
                TableColumn tc=new TableColumn();
1492
                tc.setWidth(40);
1493
                tc.setResizable(false);
1494
                getTable().addColumn(tc);
1495
        }
1496
        public static void main(String[] args) {
1497
                JTextField tf=new JTextField("hola");
1498
                tf.selectAll();
1499
                JFrame frame=new JFrame();
1500
                frame.getContentPane().add(tf);
1501
                frame.show(true);
1502
        }
1503

    
1504
        public void stopEditingCell() {
1505
            if (table.isEditing()) {
1506
                    // TODO: finalizar la edicion de la columna
1507
                    this.table.getCellEditor().stopCellEditing();
1508
                    this.refresh();
1509
            }
1510

    
1511
        }
1512

    
1513
        public void cancelEditingCell() {
1514
            if (table.isEditing()) {
1515
                    // TODO: finalizar la edicion de la columna
1516
                    this.table.getCellEditor().cancelCellEditing();
1517
                    this.refresh();
1518
            }
1519

    
1520
        }
1521

    
1522
        public void processEvent(EditionEvent e) {
1523
                if (e.getChangeType() == EditionEvent.STOP_EDITION)
1524
                {
1525
                        refreshControls();
1526
                }
1527

    
1528
        }
1529

    
1530
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1531
                // TODO Auto-generated method stub
1532

    
1533
        }
1534

    
1535
        public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
1536
                // TODO Auto-generated method stub
1537

    
1538
        }
1539

    
1540
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1541
                // TODO Auto-generated method stub
1542

    
1543
        }
1544

    
1545
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1546
                try {
1547
//                        getModel().createAlias();
1548
                        clearSelectedFields();
1549
//                        refresh();
1550
                        refreshControls();
1551
                // ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
1552
                } catch (DriverLoadException e1) {
1553
                        // TODO Auto-generated catch block
1554
                        e1.printStackTrace();
1555
                /* } catch (DriverException e1) {
1556
                        // TODO Auto-generated catch block
1557
                        e1.printStackTrace(); */
1558
                }
1559

    
1560
        }
1561
}