KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > jawe > xml > panels > XMLTablePanel


1 /* XMLTablePanel.java
2  *
3  * Authors:
4  * Stefanovic Nenad chupo@iis.ns.ac.yu
5  * Bojanic Sasa sasaboy@neobee.net
6  * Puskas Vladimir vpuskas@eunet.yu
7  * Pilipovic Goran zboniek@uns.ac.yu
8  *
9  */

10
11
12 package org.enhydra.jawe.xml.panels;
13
14 import javax.swing.*;
15
16 import java.awt.Color JavaDoc;
17 import java.awt.Component JavaDoc;
18 import java.awt.Dimension JavaDoc;
19 import java.awt.Point JavaDoc;
20 import java.awt.Rectangle JavaDoc;
21 import java.awt.event.ActionEvent JavaDoc;
22 import java.awt.event.ActionListener JavaDoc;
23 import java.awt.event.KeyEvent JavaDoc;
24 import java.awt.event.MouseAdapter JavaDoc;
25 import java.awt.event.MouseEvent JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Vector JavaDoc;
30 import javax.swing.event.ListSelectionEvent JavaDoc;
31 import javax.swing.event.ListSelectionListener JavaDoc;
32 import javax.swing.table.DefaultTableModel JavaDoc;
33 import javax.swing.table.TableCellRenderer JavaDoc;
34 import javax.swing.table.TableColumn JavaDoc;
35 import javax.swing.table.TableColumnModel JavaDoc;
36 import org.enhydra.jawe.xml.XMLCollection;
37 import org.enhydra.jawe.xml.XMLCollectionElement;
38 import org.enhydra.jawe.xml.XMLComplexElement;
39 import org.enhydra.jawe.xml.XMLElement;
40 import org.enhydra.jawe.xml.XMLElementDialog;
41 import org.enhydra.jawe.xml.XMLUtil;
42
43 import org.enhydra.jawe.xml.panels.tablesorting.*;
44
45 /**
46  * Creates a table panel.
47  */

48 public class XMLTablePanel extends XMLPanel {
49
50    public static Color JavaDoc FOREIGN_EL_COLOR_BKG=Color.lightGray;
51    public static Color JavaDoc SPEC_EL_COLOR_BKG=Color.orange;
52
53    protected static Dimension JavaDoc miniTableDimension=new Dimension JavaDoc(300,75);
54    protected static Dimension JavaDoc smallTableDimension=new Dimension JavaDoc(400,200);
55    protected static Dimension JavaDoc mediumTableDimension=new Dimension JavaDoc(600,200);
56    protected static Dimension JavaDoc largeTableDimension=new Dimension JavaDoc(800,200);
57
58    private static XMLElement toHack=new XMLElement();
59    /**
60     * Object which we are replacing from one place to another within
61     * the list by draging it.
62     */

63    private Object JavaDoc replacingObject;
64    /**
65     * Index of the object which we are replacing from one place to another
66     * within the list by draging it.
67     */

68    private int startReplaceIndex;
69    /**
70     * The new index of the object which we are replacing from one place
71     * to another within the list by draging it.
72     */

73    private int endReplaceIndex;
74    /** Indicates if object is beeing draged. */
75    private boolean dragging=false;
76    /**
77     * Indicates if the code for changing object position within the list
78     * is executed.
79     */

80    private boolean changing=false;
81
82    public XMLTablePanel (XMLCollection myOwner) {
83       this(myOwner,"");
84    }
85
86    public XMLTablePanel (XMLCollection myOwner,String JavaDoc title) {
87       this(myOwner,title,true,false);
88    }
89
90    public XMLTablePanel (XMLCollection myOwner,
91                          String JavaDoc title,
92                          boolean hasBorder,
93                          boolean automaticWidth) {
94       this(myOwner,title,hasBorder,automaticWidth,false);
95    }
96
97    public XMLTablePanel (XMLCollection myOwner,
98                          String JavaDoc title,
99                          boolean hasBorder,
100                          boolean automaticWidth,
101                          boolean miniDimension) {
102       this(myOwner,title,hasBorder,automaticWidth,miniDimension,true,true);
103    }
104
105    public XMLTablePanel (XMLCollection myOwner,
106                          String JavaDoc title,
107                          boolean hasBorder,
108                          boolean automaticWidth,
109                          boolean miniDimension,
110                          final boolean colors,
111                          final boolean showArrows) {
112
113       super(myOwner,2,title,XMLPanel.BOX_LAYOUT,false,hasBorder);
114
115       // creating a table which do not allow cell editing
116
Vector JavaDoc columnNames=new Vector JavaDoc();
117       int noOfVisibleColumns=0;
118       columnNames.add("Object");
119       Collection JavaDoc c=myOwner.getElementStructure();
120       Iterator JavaDoc it=c.iterator();
121       while (it.hasNext()) {
122          XMLElement el=(XMLElement)it.next();
123          columnNames.add(el.toLabel());
124          noOfVisibleColumns++;
125       }
126
127
128       JTable allItems=new SortingTable(this,new Vector JavaDoc(),columnNames) {
129          public boolean isCellEditable(int row, int col) {
130             return false;
131          }
132          // This table colors elements depending on their owner
133
public Component JavaDoc prepareRenderer(TableCellRenderer JavaDoc renderer,
134                                           int rowIndex, int vColIndex) {
135             Component JavaDoc c = super.prepareRenderer(renderer, rowIndex, vColIndex);
136             if (!isCellSelected(rowIndex, vColIndex) && colors) {
137                XMLElement el=(XMLElement)getValueAt(rowIndex,0);
138                if (el instanceof XMLCollectionElement) {
139                   XMLCollectionElement cel=(XMLCollectionElement)el;
140                   XMLCollection celOwner=cel.getCollection();
141                   if (celOwner==null) {
142                      c.setBackground(SPEC_EL_COLOR_BKG);
143                   } else if (!celOwner.equals(getOwner())) {
144                      c.setBackground(FOREIGN_EL_COLOR_BKG);
145                   } else {
146                      c.setBackground(getBackground());
147                   }
148                } else {
149                   c.setBackground(getBackground());
150                }
151             }
152             return c;
153          }
154
155       };
156
157       int[] invisibleFieldOrdinals=myOwner.getInvisibleTableFieldOrdinals();
158
159       TableColumnModel JavaDoc tcm=allItems.getColumnModel();
160       TableColumn JavaDoc column;
161       // setting the first column (object column) to be invisible
162
column = allItems.getColumnModel().getColumn(0);
163       column.setMinWidth(0);
164       column.setMaxWidth(0);
165       column.setPreferredWidth(0);
166       column.setResizable(false);
167       // setting fields that will not be displayed within the table
168
if (invisibleFieldOrdinals!=null && invisibleFieldOrdinals.length>0) {
169          noOfVisibleColumns-=invisibleFieldOrdinals.length;
170          for (int i=0; i<invisibleFieldOrdinals.length; i++) {
171             column = allItems.getColumnModel().getColumn(invisibleFieldOrdinals[i]+1);
172             column.setMinWidth(0);
173             column.setMaxWidth(0);
174             column.setPreferredWidth(0);
175             column.setResizable(false);
176          }
177       }
178
179       // setting some table properties
180
allItems.setColumnSelectionAllowed(false);
181       allItems.setRowSelectionAllowed(true);
182       allItems.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
183       allItems.getTableHeader().setReorderingAllowed(false);
184
185       // fills Table
186
DefaultTableModel JavaDoc dtm=(DefaultTableModel JavaDoc)allItems.getModel();
187       it=myOwner.getTableElements().iterator();
188       while (it.hasNext()) {
189          XMLElement elem=null;
190          if (it.hasNext()) {
191             elem=(XMLElement)it.next();
192          }
193          Vector JavaDoc v=null;
194          if (elem instanceof XMLComplexElement) {
195             v=new Vector JavaDoc(((XMLComplexElement)elem).toComplexTypeValues());
196          } else {
197             v=new Vector JavaDoc();
198             v.add(elem.toString());
199          }
200          v.add(0,elem);
201          dtm.addRow(v);
202       }
203
204
205       // mouse listener for editing on double-click
206
allItems.addMouseListener(new MouseAdapter JavaDoc() {
207                public void mouseClicked (MouseEvent JavaDoc me) {
208                   if (me.getClickCount()>1) {
209                      editElementDialog();
210                   }
211                }
212
213                /** Marks the object which place within the table will be changed.*/
214                public void mousePressed (MouseEvent JavaDoc me) {
215                   if (!showArrows ||
216                          (getOwner().isReadOnly() && ((XMLCollection)getOwner()).getOwner().isReadOnly())) return;
217                   dragging=true;
218                   JTable t=getTable();
219                   replacingObject=null;
220                   startReplaceIndex=-1;
221                   try {
222                      startReplaceIndex=t.getSelectedRow();
223                      if (startReplaceIndex>=0) {
224                         replacingObject=t.getValueAt(startReplaceIndex,0);
225                      }
226                   } catch (Exception JavaDoc ex) {}
227                }
228
229                /** Just indicates that dragging is over.*/
230                public void mouseReleased (MouseEvent JavaDoc me) {
231                   dragging=false;
232                }
233             });
234
235       /** Changes position of object within the list.*/
236       if (showArrows &&
237              (!(myOwner.isReadOnly() && ((XMLCollection)getOwner()).getOwner().isReadOnly()))) {
238
239          ListSelectionModel rowSM = allItems.getSelectionModel();
240          rowSM.addListSelectionListener(new ListSelectionListener JavaDoc() {
241                   public void valueChanged (ListSelectionEvent JavaDoc lse) {
242                      if (dragging && !changing) {
243                         changing=true;
244                         JTable t=getTable();
245                         endReplaceIndex=-1;
246                         try {
247                            endReplaceIndex=t.getSelectedRow();
248                         } catch (Exception JavaDoc ex) {}
249                         XMLCollection owncol=(XMLCollection)getOwner();
250                         //System.out.println("ro="+replacingObject+", sri="+startReplaceIndex+", eri="+endReplaceIndex+", ocs="+owncol.size()+"occol="+owncol.toCollection());
251
if (replacingObject==null || startReplaceIndex==-1 || endReplaceIndex==-1 ||
252                             startReplaceIndex==endReplaceIndex || (owncol.size()-1)<startReplaceIndex ||
253                                (owncol.size()-1)<endReplaceIndex || !owncol.toCollection().contains(replacingObject)) {
254                            changing=false;
255                            return;
256                         }
257
258                         DefaultTableModel JavaDoc dtm=(DefaultTableModel JavaDoc)t.getModel();
259                         Vector JavaDoc v=null;
260                         if (replacingObject instanceof XMLComplexElement) {
261                            v=new Vector JavaDoc(((XMLComplexElement)replacingObject).toComplexTypeValues());
262                         } else {
263                            v=new Vector JavaDoc();
264                            v.add(replacingObject.toString());
265                         }
266                         // add object itself to the first column (it is invisible column)
267
v.add(0,replacingObject);
268                         dtm.removeRow(startReplaceIndex);
269                         dtm.insertRow(endReplaceIndex,v);
270                         ((XMLCollection)getOwner()).remove(replacingObject);
271                         ((ArrayList JavaDoc)((XMLCollection)getOwner()).
272                             toCollection()).add(endReplaceIndex,replacingObject);
273                         try {
274                            t.setRowSelectionInterval(endReplaceIndex,endReplaceIndex);
275                         } catch (Exception JavaDoc ex) {}
276
277                         ((XMLElementDialog)getDialog()).notifyListeners((XMLElement)replacingObject); // this is dirty hack
278

279                         startReplaceIndex=endReplaceIndex;
280                         changing=false;
281                      }
282                   }
283                });
284          allItems.setToolTipText(
285             XMLUtil.getLanguageDependentString("MessageDragItemToChangeItsPosition"));
286       }
287
288       allItems.getInputMap(JComponent.WHEN_FOCUSED).
289          put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false),"edit");
290       allItems.getActionMap().put("edit",new AbstractAction() {
291                public void actionPerformed(ActionEvent JavaDoc e) {
292                   editElementDialog();
293                }
294             });
295
296       allItems.getInputMap(JComponent.WHEN_FOCUSED).
297          put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0,false),"delete");
298       allItems.getActionMap().put("delete",new AbstractAction() {
299                public void actionPerformed(ActionEvent JavaDoc e) {
300                   deleteElementDialog();
301                }
302             });
303
304       allItems.getInputMap(JComponent.WHEN_FOCUSED).
305          put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0,false),"cancel");
306       allItems.getActionMap().put("cancel",new AbstractAction() {
307                public void actionPerformed(ActionEvent JavaDoc e) {
308                   XMLElementDialog d=((XMLElementDialog)getDialog());
309                   d.setCanceled(true);
310                   d.dispose();
311                }
312             });
313
314       // creates panel
315
JScrollPane allItemsPane=new JScrollPane();
316       allItemsPane.setViewportView(allItems);
317       Dimension JavaDoc tDim;
318       if (miniDimension) {
319          tDim=new Dimension JavaDoc(miniTableDimension);
320       } else if (noOfVisibleColumns<=3) {
321          tDim=new Dimension JavaDoc(smallTableDimension);
322       } else if (noOfVisibleColumns<=5) {
323          tDim=new Dimension JavaDoc(mediumTableDimension);
324       } else {
325          tDim=new Dimension JavaDoc(largeTableDimension);
326       }
327
328       if (automaticWidth) {
329          tDim.width=allItems.getPreferredScrollableViewportSize().width;
330       }
331       allItems.setPreferredScrollableViewportSize(new Dimension JavaDoc(tDim));
332
333       add(allItemsPane);
334       //add(Box.createVerticalGlue());
335

336       if (showArrows) {
337          JPanel p=new JPanel();
338          p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
339
340          JButton buttonUp=new JButton();
341          java.net.URL JavaDoc u = XMLUtil.getResource("ArrowUpImage");
342          if (u!=null) {
343             buttonUp.setIcon(new ImageIcon(u));
344          }
345          buttonUp.setEnabled(!(myOwner.isReadOnly() && ((XMLCollection)getOwner()).getOwner().isReadOnly()));
346          buttonUp.addActionListener(new ActionListener JavaDoc() {
347                   public void actionPerformed(ActionEvent JavaDoc e) {
348                      moveItem(0);
349                   }
350                });
351          buttonUp.setPreferredSize(new Dimension JavaDoc(25,25));
352          JButton buttonDown=new JButton();
353          u = XMLUtil.getResource("ArrowDownImage");
354          if (u!=null) {
355             buttonDown.setIcon(new ImageIcon(u));
356          }
357          buttonDown.setEnabled(!(myOwner.isReadOnly() && ((XMLCollection)getOwner()).getOwner().isReadOnly()));
358          buttonDown.addActionListener(new ActionListener JavaDoc() {
359                   public void actionPerformed(ActionEvent JavaDoc e) {
360                      moveItem(1);
361                   }
362                });
363          buttonDown.setPreferredSize(new Dimension JavaDoc(25,25));
364          p.add(buttonUp);
365          p.add(Box.createVerticalGlue());
366          p.add(buttonDown);
367          add(Box.createRigidArea(new Dimension JavaDoc(5,0)));
368          add(p);
369       }
370    }
371
372    public JTable getTable () {
373       JScrollPane jsp=(JScrollPane)getComponent(0);
374       JViewport jvp=(JViewport)jsp.getComponent(0);
375       JTable jt=(JTable)jvp.getComponent(0);
376       return jt;
377    }
378
379    public XMLElement getSelectedElement () {
380       JTable t=getTable();
381       int row=t.getSelectedRow();
382       if (row>=0) {
383          return (XMLElement)t.getValueAt(row, 0);
384       }
385       return null;
386
387    }
388
389    public void setSelectedElement (Object JavaDoc el) {
390       try {
391          JTable t=getTable();
392          int rc=t.getRowCount();
393          if (rc>0) {
394             for (int i=0; i<rc; i++) {
395                if (el.equals(t.getValueAt(i,0))) {
396                   t.setRowSelectionInterval(i,i);
397
398                   // focus the row
399

400                   JViewport viewport = (JViewport)t.getParent();
401                   // This rectangle is relative to the table where the
402
// northwest corner of cell (0,0) is always (0,0).
403
Rectangle JavaDoc rect = t.getCellRect(i,0,true);
404                   // The location of the viewport relative to the table
405
Point JavaDoc pt = viewport.getViewPosition();
406                   // Translate the cell location so that it is relative
407
// to the view, assuming the northwest corner of the
408
// view is (0,0)
409
rect.setLocation(rect.x-pt.x, rect.y-pt.y);
410                   // Scroll the area into view
411
viewport.scrollRectToVisible(rect);
412
413                   break;
414                }
415             }
416          }
417       } catch (Exception JavaDoc ex) {}
418    }
419
420
421    public void modifyElement(XMLElement e) {
422       SortingTable t=(SortingTable)getTable();
423       int row=t.getSelectedRow();
424       DefaultTableModel JavaDoc dtm=(DefaultTableModel JavaDoc)t.getModel();
425       Vector JavaDoc v=null;
426       if (e instanceof XMLComplexElement) {
427          v=new Vector JavaDoc(((XMLComplexElement)e).toComplexTypeValues());
428       } else {
429          v=new Vector JavaDoc();
430          v.add(e.toString());
431       }
432       // add object itself to the first column (it is invisible column)
433
v.add(0,e);
434       dtm.removeRow(row);
435       dtm.insertRow(row,v);
436       try {
437          t.setRowSelectionInterval(row,row);
438       } catch (Exception JavaDoc ex) {}
439       t.performSorting(null);
440    }
441
442    public void removeElement(XMLElement e) {
443       ((XMLCollection)getOwner()).remove(getSelectedElement());
444       JTable t=getTable();
445       int row=t.getSelectedRow();
446       DefaultTableModel JavaDoc dtm=(DefaultTableModel JavaDoc)t.getModel();
447       dtm.removeRow(row);
448       try {
449          if (row==0) {
450             row++;
451          }
452          t.setRowSelectionInterval(row-1,row-1);
453       } catch (Exception JavaDoc ex) {}
454       t.requestFocus();
455    }
456
457    private void editElementDialog () {
458       XMLElement editElement=getSelectedElement();
459       if (editElement != null) {
460          XMLElementDialog de=new XMLElementDialog(getDialog(),
461                                                   editElement.toLabel()+" '"+editElement.toString()+"' - "+
462                                                      XMLUtil.getLanguageDependentString("EditingKey"));
463          de.editXMLElement(editElement.getPanel(),true,false);
464          if (!de.isCanceled()) {
465             modifyElement(editElement);
466             ((XMLCollection)getOwner()).onElementModified(editElement);
467          }
468       } else {
469          JOptionPane.showMessageDialog(getDialog(),
470                                        XMLUtil.getLanguageDependentString("WarningEmptySelectionToEditOrDelete"),
471                                        XMLUtil.getLanguageDependentString("Title"),
472                                        JOptionPane.WARNING_MESSAGE);
473       }
474       getTable().requestFocus();
475    }
476
477    private void deleteElementDialog () {
478       XMLElement deleteElement=getSelectedElement();
479       if (deleteElement == null) {
480          JOptionPane.showMessageDialog(getDialog(),
481                                        XMLUtil.getLanguageDependentString("WarningEmptySelectionToEditOrDelete"),
482                                        XMLUtil.getLanguageDependentString("Title"),
483                                        JOptionPane.WARNING_MESSAGE);
484       } else if (deleteElement.isReadOnly()) {
485          JOptionPane.showMessageDialog(getDialog(),
486                                        XMLUtil.getLanguageDependentString(((XMLCollection)getOwner()).
487                                                                              getReadOnlyMessageName(deleteElement)),
488                                        XMLUtil.getLanguageDependentString("Title"),
489                                        JOptionPane.WARNING_MESSAGE);
490       } else if (!((XMLCollection)getOwner()).canRemoveElement(deleteElement)) {
491          JOptionPane.showMessageDialog(getDialog(),
492                                        XMLUtil.getLanguageDependentString(((XMLCollection)getOwner()).
493                                                                              getInUseMessageName(deleteElement)),
494                                        XMLUtil.getLanguageDependentString("Title"),
495                                        JOptionPane.WARNING_MESSAGE);
496       } else {
497          int yn=JOptionPane.showConfirmDialog(getDialog(),
498                                               XMLUtil.getLanguageDependentString(
499                                                  "MessageDoYouReallyWantToRemoveSelectedItem"),
500                                               deleteElement.toLabel()+" - "+
501                                                  XMLUtil.getLanguageDependentString("DeletingKey"),
502                                               JOptionPane.YES_NO_OPTION);
503          if (yn==JOptionPane.YES_OPTION) {
504             removeElement(deleteElement);
505             ((XMLCollection)getOwner()).onElementDeleted(deleteElement);
506             XMLElementDialog.notifyListeners(deleteElement); // this is dirty hack
507
}
508       }
509
510    }
511
512    private void moveItem (int upOrDown) {
513       changing=true;
514       JTable t=getTable();
515       XMLElement rObject=null;
516       int sri=-1;
517       try {
518          sri=t.getSelectedRow();
519          if (sri>=0) {
520             rObject=(XMLElement)t.getValueAt(sri,0);
521          }
522       } catch (Exception JavaDoc ex) {}
523       XMLCollection owncol=(XMLCollection)getOwner();
524
525       int eri=sri;
526       if (eri==-1) {
527          // do nothing
528
} else if (upOrDown==0) {
529          eri--;
530       } else {
531          eri++;
532       }
533
534       if (rObject==null || sri==-1 || eri==-1 || eri==sri || (owncol.size()-1)<sri ||
535              (owncol.size()-1)<eri ||
536           !owncol.toCollection().contains(rObject)) {
537          changing=false;
538          return;
539       }
540
541       DefaultTableModel JavaDoc dtm=(DefaultTableModel JavaDoc)t.getModel();
542       Vector JavaDoc v=null;
543       if (rObject instanceof XMLComplexElement) {
544          v=new Vector JavaDoc(((XMLComplexElement)rObject).toComplexTypeValues());
545       } else {
546          v=new Vector JavaDoc();
547          v.add(rObject.toString());
548       }
549       // add object itself to the first column (it is invisible column)
550
v.add(0,rObject);
551       dtm.removeRow(sri);
552       dtm.insertRow(eri,v);
553       ((XMLCollection)getOwner()).remove(rObject);
554       ((ArrayList JavaDoc)((XMLCollection)getOwner()).toCollection()).add(eri,rObject);
555
556       try {
557          t.setRowSelectionInterval(eri,eri);
558       } catch (Exception JavaDoc ex) {}
559
560       ((XMLElementDialog)getDialog()).notifyListeners(rObject); // this is dirty hack
561

562       changing=false;
563    }
564
565 }
566
567
568
Popular Tags