KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > ide > editors > ui > DDTablePanel


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 /*
20  * DDTablePanel.java -- synopsis.
21  *
22  */

23
24 package org.netbeans.modules.j2ee.sun.ide.editors.ui;
25
26 import java.awt.*;
27 import java.awt.event.*;
28 import java.util.*;
29 import java.text.*;
30 import javax.swing.*;
31 import javax.swing.border.*;
32 import javax.swing.table.*;
33 import javax.swing.event.*;
34 import java.lang.ref.*;
35
36 import org.openide.explorer.propertysheet.editors.*;
37 import org.openide.*;
38 import org.openide.util.*;
39
40 /**
41  * Panel containing a JTable for display of Deployment
42  * Descriptor array values, and an "add" and "remove" button.
43  *
44  * @author Joe Warzecha
45  */

46 //
47
// 29-may-2001
48
// Changes for bug 4457984. Added an ancestor listener to check
49
// for the user cancelling. Changed the call to the addRowAt so
50
// the newly created row is passed to the next level, and called
51
// newElementCancelled in the case where the user cancels the creation
52
// of a new row. (joecorto)
53
//
54
public class DDTablePanel extends JPanel
55               implements EnhancedCustomPropertyEditor {
56
57     static final ResourceBundle bundle = NbBundle.getBundle
58                                                     (DDTablePanel.class);
59
60     private DDTableModel model;
61
62     private JScrollPane scrollPane;
63     private JTable tab;
64     private JButton addButton;
65     private JButton editButton;
66     private JButton removeButton;
67     private int sortCol;
68     private Dialog editDialog;
69                 
70     public DDTablePanel (DDTableModel m, String JavaDoc [] toolTips) {
71     initComponents (m, toolTips, true, true, true, 500, 70, 12);
72     }
73
74     public DDTablePanel (DDTableModel m, String JavaDoc [] toolTips, int insetVal) {
75     initComponents (m, toolTips, true, true, true, 500, 70, insetVal);
76     }
77
78     public DDTablePanel (DDTableModel m, String JavaDoc[] toolTips, boolean allowAdd,
79              boolean allowRemove) {
80         initComponents (m, toolTips, allowAdd, allowRemove, true, 500, 70, 12);
81     }
82
83     public DDTablePanel (DDTableModel m) {
84         initComponents (m, new String JavaDoc [0], false, false, false, 500, 70, 12);
85     }
86     
87     public DDTablePanel (DDTableModel m, String JavaDoc [] toolTips, int width, int height){
88         initComponents (m, toolTips, true, true, true, width, height, 12);
89     }
90
91     /** This method is called from within the constructor to
92      * initialize the form.
93      */

94     private void initComponents (DDTableModel m, String JavaDoc [] toolTips,
95                  boolean allowAdd, boolean allowRemove,
96                  boolean allowEdit, int width, int height,
97                  int insetVal) {
98     JPanel buttonPanel;
99
100     model = m;
101     sortCol = -1;
102     
103     setBorder (new EmptyBorder (insetVal, insetVal, insetVal, insetVal));
104     setLayout (new BorderLayout ());
105
106     scrollPane = new javax.swing.JScrollPane JavaDoc ();
107     tab = new JTable (model);
108     tab.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
109
110     scrollPane.setViewportView (tab);
111     add (scrollPane, BorderLayout.CENTER);
112
113     buttonPanel = new JPanel ();
114     buttonPanel.setLayout (new FlowLayout ());
115
116
117     addButton = new JButton ();
118 // addButton.setText (bundle.getString ("CTL_Add"));
119
org.openide.awt.Mnemonics.setLocalizedText(addButton, bundle.getString ("CTL_Add")); // NOI18N
120
addButton.addActionListener (new ActionListener () {
121         public void actionPerformed (ActionEvent evt) {
122             addButtonActionPerformed (evt);
123         }
124     });
125     buttonPanel.add (addButton);
126     addButton.setVisible(allowAdd);
127         
128         editButton = new JButton ();
129 // editButton.setText (bundle.getString ("CTL_Edit"));
130
org.openide.awt.Mnemonics.setLocalizedText(editButton, bundle.getString ("CTL_Edit")); // NOI18N
131
editButton.addActionListener (new ActionListener () {
132         public void actionPerformed (ActionEvent evt) {
133         editButtonActionPerformed (evt);
134         }
135     });
136     buttonPanel.add (editButton);
137
138     removeButton = new JButton ();
139 // removeButton.setText (bundle.getString ("CTL_Remove"));
140
org.openide.awt.Mnemonics.setLocalizedText(removeButton, bundle.getString ("CTL_Remove")); // NOI18N
141
removeButton.addActionListener (new ActionListener () {
142         public void actionPerformed (ActionEvent evt) {
143             removeButtonActionPerformed (evt);
144         }
145     });
146     buttonPanel.add (removeButton);
147     removeButton.setEnabled(false);
148     removeButton.setVisible(allowRemove);
149
150     add (buttonPanel, BorderLayout.SOUTH);
151     
152     if (model instanceof SortableDDTableModel) {
153         addMouseListenerToHeader((SortableDDTableModel)model);
154     }
155
156     setHeaderToolTips (toolTips);
157
158     if ((allowRemove) || (allowEdit)) {
159         tab.getSelectionModel().addListSelectionListener(
160              new ListSelectionListener() {
161                  public void valueChanged(ListSelectionEvent e) {
162                  if ((!e.getValueIsAdjusting()) &&
163                     (tab.getRowCount () > 0)) {
164                      boolean rowSelected = tab.getSelectedRow() != -1;
165                      removeButton.setEnabled(rowSelected);
166                  editButton.setEnabled(rowSelected);
167                  }
168                  }
169              }
170             );
171     }
172
173     if (allowEdit) {
174         tab.addMouseListener(new MouseAdapter() {
175             public void mouseClicked(MouseEvent me) {
176                 if (me.getClickCount() == 2) {
177                 int row = tab.rowAtPoint(me.getPoint());
178                 if (row != -1) {
179                     tab.setRowSelectionInterval(row,row);
180                     editButtonActionPerformed(null);
181                 }
182                 }
183             }
184         });
185     }
186
187     editButton.setEnabled(false);
188     editButton.setVisible (allowEdit);
189     int tableWidth = initColumnSizes();
190     if (tableWidth > width) {
191         width = tableWidth;
192     }
193     tab.setPreferredScrollableViewportSize (new Dimension(width, height));
194     this.addAncestorListener(new AListener()); // BUG 4457984
195
initAccessibility();
196     }
197
198     private void initAccessibility(){
199         getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_DDTablePanel"));
200         addButton.getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_add"));
201         editButton.getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_edit"));
202         removeButton.getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_remove"));
203         tab.getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_DDTable"));
204         tab.getAccessibleContext().setAccessibleName(model.getModelName());
205     }
206
207     public void addListSelectionListener (ListSelectionListener l) {
208     tab.getSelectionModel ().addListSelectionListener (l);
209     }
210
211     public void addVerticalScrollBarAdjustmentListener (AdjustmentListener l) {
212     scrollPane.getVerticalScrollBar ().addAdjustmentListener (l);
213     }
214
215     public void setVerticalScrollBarValue (int val) {
216     int curVal = scrollPane.getVerticalScrollBar ().getValue ();
217     if (curVal != val) {
218         scrollPane.getVerticalScrollBar ().setValue (val);
219     }
220     }
221     
222     public void linkLabel(JLabel label)
223     {
224         label.setLabelFor(tab);
225     }
226
227     public Color getHeaderColor () {
228     if (tab.getColumnCount () < 1) {
229         return Color.black;
230     }
231
232     TableColumn c = tab.getColumnModel ().getColumn (0);
233     TableCellRenderer cellR = c.getHeaderRenderer ();
234     Component comp = cellR.getTableCellRendererComponent
235                         (tab, c.getHeaderValue (), false,
236                      false, -1, 0);
237     return comp.getForeground ();
238     }
239
240     public int getSelectedRow () {
241     return tab.getSelectedRow ();
242     }
243
244     public void setSelectedRow (int row) {
245     if (row == -1) {
246         tab.clearSelection ();
247     } else {
248         tab.addRowSelectionInterval (row, row);
249     }
250     }
251
252     private void setHeaderToolTips (String JavaDoc [] toolTips) {
253     /*
254      * A change was made in the jdk, such that in jdk1.3, the
255      * TableColumn may not have a TableCellRenderer for the table
256      * headers. Now, that renderer is created in the JTableHeader
257      * instead. Because of this inconsistency, I added code
258      * which determines if the TableColumn has a default renderer
259      * and if not, creates one (the code is actually "stolen" from
260      * the jdk1.2.2 source).
261      */

262
263     for (int i = 0; i < model.getColumnCount(); i++) {
264         TableColumn c = tab.getColumnModel ().getColumn (i);
265         TableCellRenderer cellR = c.getHeaderRenderer ();
266         
267         DefaultTableCellRenderer label = new DefaultTableCellRenderer() {
268                  public Component getTableCellRendererComponent (JTable table,
269                                                                  Object JavaDoc value,
270                                                    boolean isSelected,
271                                                              boolean hasFocus,
272                                       int row, int column)
273                  {
274                       if (table != null) {
275                           JTableHeader header = table.getTableHeader();
276                           if (header != null) {
277                               setForeground(header.getForeground());
278                               setBackground(header.getBackground());
279                   int style =
280                                 (tab.convertColumnIndexToModel(column) ==
281                                  sortCol)?Font.BOLD:Font.PLAIN;
282                               setFont(header.getFont().deriveFont(style));
283               }
284               }
285  
286                       setText ((value == null) ? "" : value.toString ()); // NOI18N
287
setBorder(UIManager.getBorder("TableHeader.cellBorder")); // NOI18N
288
return this;
289          }
290         };
291             label.setHorizontalAlignment(JLabel.CENTER);
292         c.setHeaderRenderer (label);
293         cellR = label;
294
295         Component comp = cellR.getTableCellRendererComponent
296                         (tab, c.getHeaderValue (), false,
297                      false, -1, i);
298         if ((comp != null) && (comp instanceof JComponent)
299          && i<toolTips.length) {
300             JComponent jComp = (JComponent) comp;
301             jComp.setToolTipText (toolTips [i]);
302         }
303         }
304     }
305
306     private int maxSize(int col) {
307         Component c = null;
308     int max = 0;
309         for (int i = 0; i < model.getRowCount(); i++) {
310         c = tab.getDefaultRenderer(model.getColumnClass(col)).
311                              getTableCellRendererComponent(
312                                  tab, model.getValueAt(i,col),
313                                  false, false, i, col);
314         if (c.getPreferredSize().width > max) {
315             max = c.getPreferredSize().width;
316         }
317         }
318     return max;
319     }
320
321     private int initColumnSizes() {
322     int totWidth = tab.getIntercellSpacing().width * model.getColumnCount();
323         for (int i = 0; i < model.getColumnCount(); i++) {
324             TableColumn column = tab.getColumnModel().getColumn(i);
325
326             Component comp = column.getHeaderRenderer().
327                              getTableCellRendererComponent(
328                                  null, column.getHeaderValue(),
329                                  false, false, 0, 0);
330         /*
331          * Note the +6 is so that there will be some "white" space
332          * on each side of the text in the header.
333          */

334             int headerWidth = comp.getPreferredSize().width + 6;
335             int cellWidth = maxSize(i);
336         totWidth += Math.max (headerWidth, cellWidth);
337             column.setPreferredWidth(Math.max(headerWidth, cellWidth));
338         }
339     return totWidth;
340     }
341
342     public void setCellEditor (int col, TableCellEditor cEdit) {
343     tab.getColumnModel ().getColumn (col).setCellEditor (cEdit);
344     }
345
346     private void addButtonActionPerformed(ActionEvent evt) {
347     editRow(tab.getSelectedRow(), true);
348     }
349
350     private void closeEditDialog() {
351         editDialog.setVisible(false);
352         editDialog.dispose();
353     editDialog = null;
354     }
355
356     public void editSelectedRow () {
357     editRow (tab.getSelectedRow (), false);
358     }
359
360     private void editRow(final int row, final boolean isNew) {
361         final DDTableModelEditor editor = model.getEditor();
362     //
363
// Changed how new is done for bug 4457984.
364
//
365
final Object JavaDoc obj = (isNew?model.makeNewElement():model.getValueAt(row));
366     editor.setValue(obj);
367     JPanel p = new JPanel();
368     JPanel editorPanel = editor.getPanel ();
369     HelpCtx hCtx = null; // HelpCtx.findHelp (editorPanel);
370
if (hCtx != null) {
371         HelpCtx.setHelpIDString (p, hCtx.getHelpID ());
372     }
373     p.add(BorderLayout.NORTH, editorPanel);
374         p.getAccessibleContext().setAccessibleDescription(editorPanel.getAccessibleContext().getAccessibleDescription());
375     String JavaDoc editType = isNew?bundle.getString("TTL_ADD"):
376                             bundle.getString("TTL_EDIT");
377     String JavaDoc title = MessageFormat.format(bundle.getString("TTL_DIALOG"),
378                         new Object JavaDoc[] {
379                                             editType,
380                         model.getModelName()
381                                             });
382
383     if (p.getAccessibleContext().getAccessibleDescription () == null) {
384         p.getAccessibleContext().setAccessibleDescription (title);
385     }
386
387         DialogDescriptor dd = new DialogDescriptor(p, title,
388             true, NotifyDescriptor.OK_CANCEL_OPTION, null,
389             DialogDescriptor.BOTTOM_ALIGN, null,
390             new ActionListener() {
391                 public void actionPerformed(ActionEvent evt) {
392            if (evt.getSource() != NotifyDescriptor.OK_OPTION) {
393                if (isNew) {
394                 //
395
// BUG 4457984 - the new was cancelled, so
396
// tell the model. This allows the app server
397
// api to be told.
398
//
399
model.newElementCancelled(obj);
400                }
401            } else {
402                        java.util.List JavaDoc errors =
403                            model.isValueValid
404                     (editor.getValue (), isNew?-1:row);
405                        if (! errors.isEmpty()) {
406                            Component errorComp = getErrorComponent (("MSG_TableErrors"),errors);// NOI18N
407
errorComp.getAccessibleContext().setAccessibleDescription(getA11yText(errors));
408                            NotifyDescriptor d = new NotifyDescriptor(errorComp,
409                                          MessageFormat.format(
410                                             bundle.getString("TTL_DIALOG"),
411                                             new Object JavaDoc[] {
412                               bundle.getString("TTL_ERROR"),
413                         model.getModelName()}),
414                      NotifyDescriptor.OK_CANCEL_OPTION,
415                      NotifyDescriptor.ERROR_MESSAGE,
416                      new Object JavaDoc[]{NotifyDescriptor.OK_OPTION},
417                      null);
418                         DialogDisplayer.getDefault().notify(d);
419                 return;
420                        } else {
421                if (!isNew) {
422                    if (! model.isEditValid
423                         (editor.getValue (), row)) {
424                    return;
425                    }
426
427                    int[] rows = tab.getSelectedRows();
428                    tab.clearSelection();
429                    model.setValueAt(row, editor.getValue());
430                    if (rows != null) {
431                    for (int i = 0; i < rows.length; i++) {
432                        tab.setRowSelectionInterval(rows[i],
433                                    rows[i]);
434                    }
435                    }
436                } else {
437                    //
438
// BUG 4457984 - pass the row created above
439
// to the next level so that it can store
440
// the original row created.
441
//
442
model.addRowAt(row >= model.getRowCount() ? model.getRowCount()-1 :
443                                               row, obj, editor.getValue());
444                }
445             }
446                    }
447            closeEditDialog();
448                 }
449             });
450         dd.setClosingOptions(new Object JavaDoc[0]);
451         // XXX workaround for issuezilla 12542
452
JButton cancel = new JButton(bundle.getString("LBL_Cancel"));
453         cancel.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_Cancel"));
454         cancel.setVerifyInputWhenFocusTarget(false);
455         dd.setOptions(new Object JavaDoc[] {
456                               NotifyDescriptor.OK_OPTION,
457                               cancel});
458         editDialog = DialogDisplayer.getDefault().createDialog(dd);
459         editDialog.setVisible(true);
460     }
461                     
462
463     private void editButtonActionPerformed (ActionEvent evt) {
464         editRow(tab.getSelectedRow(), false);
465     }
466
467     private void removeButtonActionPerformed (ActionEvent evt) {
468     int row = tab.getSelectedRow ();
469     java.util.List JavaDoc errors = model.canRemoveRow (row);
470     if (! (errors.isEmpty ())) {
471         Component c = getErrorComponent ("MSG_RemoveWarning", errors); // NOI18N
472
NotifyDescriptor.Confirmation confirmDesc =
473                            new NotifyDescriptor.Confirmation (c,
474                     bundle.getString ("CTL_Remove") +
475                     " " + model.getModelName () + " " + // NOI18N
476
bundle.getString ("TTL_WARNING"));
477             Object JavaDoc [] options = new Object JavaDoc [] { bundle.getString ("CTL_Remove"),
478                                     NotifyDescriptor.CANCEL_OPTION };
479             confirmDesc.setOptions (options);
480
481             Object JavaDoc o = DialogDisplayer.getDefault().notify(confirmDesc);
482             if (o == NotifyDescriptor.CANCEL_OPTION) {
483                 return ;
484             }
485     }
486
487     tab.removeRowSelectionInterval(row,row);
488
489     //
490
// The following is needed to make sure those rows that have
491
// associated app server properties are set up so the plug-in
492
// knows they are being deleted. Creating the editor causes
493
// the model subclasses to call the plug-in making sure it
494
// has loaded its information about these rows (See EjbRefAppSrvEditor
495
// and ejb/EditableDDRef).
496
//
497
DDTableModelEditor editor = model.getEditor();
498     editor.setValue(model.getValueAt(row));
499     model.removeRowAt (row);
500     }
501
502     private Component getErrorComponent
503                 (String JavaDoc summaryString, java.util.List JavaDoc errors) {
504     if (errors.size () == 1) {
505         return new MultiLineField ((String JavaDoc) errors.get (0));
506     }
507
508     MessageArea msg = new MessageArea ();
509     Object JavaDoc [] o = new Object JavaDoc [] { model.getModelName() };
510     msg.setText (MessageFormat.format
511                 (bundle.getString (summaryString), o));
512     Iterator iter = errors.iterator ();
513     while (iter.hasNext ()) {
514         msg.appendBulletItem ((String JavaDoc) iter.next ());
515     }
516     return msg;
517     }
518
519     private String JavaDoc getA11yText(java.util.List JavaDoc errors) {
520         Object JavaDoc [] o = new Object JavaDoc [] { model.getModelName() };
521         StringBuffer JavaDoc buf =new StringBuffer JavaDoc(MessageFormat.format(bundle.getString("MSG_TableErrors"),o));
522         for (int i=0;i<errors.size();i++) {
523             buf.append("\n"+(String JavaDoc)errors.get(i)); //NOI18N
524
}
525         return buf.toString();
526     }
527     
528     /**
529      * Add listener for table header clicks. This invokes sort on the clicked
530      * column.
531      */

532     private void addMouseListenerToHeader(final SortableDDTableModel model) {
533         MouseAdapter listMouseListener = new MouseAdapter() {
534             public void mouseClicked(MouseEvent e) {
535                 TableColumnModel columnModel = tab.getColumnModel();
536                 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
537                 int column = tab.convertColumnIndexToModel(viewColumn);
538                 if (e.getClickCount() == 1 && column != -1) {
539                     model.setSortColumn(sortCol = column);
540                 }
541             }
542         };
543         JTableHeader th = tab.getTableHeader();
544         th.addMouseListener(listMouseListener);
545     }
546
547     public Object JavaDoc getPropertyValue () throws IllegalStateException JavaDoc {
548         getPropertyValueCalled = true;
549     return model.getValue ();
550     }
551
552     boolean getPropertyValueCalled = false;
553
554     //
555
// Added to fix bug 4457984 - check for a cancel.
556
//
557
class AListener implements AncestorListener {
558     public void ancestorAdded(AncestorEvent event) {
559     }
560     public void ancestorMoved(AncestorEvent event) {
561     }
562     public void ancestorRemoved(AncestorEvent event) {
563         if (!DDTablePanel.this.isShowing()) {
564             if (getPropertyValueCalled) {
565             // User pressed OK
566
} else {
567             // User cancelled
568
DDTablePanel.this.model.editsCancelled();
569         }
570         }
571     }
572     }
573 }
574
Popular Tags