KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > explorer > view > TreeViewCellEditor


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 package org.openide.explorer.view;
20
21 import org.openide.nodes.Node;
22 import org.openide.util.NbBundle;
23
24 import java.awt.Component JavaDoc;
25 import java.awt.Point JavaDoc;
26 import java.awt.Rectangle JavaDoc;
27 import java.awt.event.ActionEvent JavaDoc;
28 import java.awt.event.FocusEvent JavaDoc;
29 import java.awt.event.FocusListener JavaDoc;
30 import java.awt.event.KeyEvent JavaDoc;
31 import java.awt.event.MouseEvent JavaDoc;
32 import java.awt.event.MouseMotionListener JavaDoc;
33
34 import java.util.EventObject JavaDoc;
35
36 import javax.swing.DefaultCellEditor JavaDoc;
37 import javax.swing.JComponent JavaDoc;
38 import javax.swing.JTextField JavaDoc;
39 import javax.swing.JTree JavaDoc;
40 import javax.swing.KeyStroke JavaDoc;
41 import javax.swing.SwingUtilities JavaDoc;
42 import javax.swing.event.CellEditorListener JavaDoc;
43 import javax.swing.event.ChangeEvent JavaDoc;
44 import javax.swing.tree.DefaultTreeCellEditor JavaDoc;
45 import javax.swing.tree.DefaultTreeCellRenderer JavaDoc;
46 import javax.swing.tree.TreeCellEditor JavaDoc;
47 import javax.swing.tree.TreePath JavaDoc;
48 import org.openide.DialogDisplayer;
49 import org.openide.NotifyDescriptor;
50 import org.openide.util.Exceptions;
51
52
53 /** In-place editor in the tree view component.
54 *
55 * @author Petr Hamernik
56 */

57 class TreeViewCellEditor extends DefaultTreeCellEditor JavaDoc implements CellEditorListener JavaDoc, FocusListener JavaDoc,
58     MouseMotionListener JavaDoc {
59     /** generated Serialized Version UID */
60     static final long serialVersionUID = -2171725285964032312L;
61
62     // Attributes
63

64     /** Indicates whether is drag and drop currently active or not */
65     boolean dndActive = false;
66
67     /** True, if the editation was cancelled by the user.
68     */

69     private boolean cancelled = false;
70
71     /** Stopped is true, if the editation is over (editingStopped is called for the
72         first time). The two variables have virtually the same function, but are kept
73         separate for code clarity.
74     */

75     private boolean stopped = false;
76
77     /** Construct a cell editor.
78     * @param tree the tree
79     */

80     public TreeViewCellEditor(JTree JavaDoc tree) {
81         //Use a dummy DefaultTreeCellEditor - we'll set up the correct
82
//icon when we fetch the editor component (see EOF). Not sure
83
//it's wildly vaulable to subclass DefaultTreeCellEditor here -
84
//we override most everything
85
super(tree, new DefaultTreeCellRenderer JavaDoc());
86
87         // deal with selection if already exists
88
if (tree.getSelectionCount() == 1) {
89             lastPath = tree.getSelectionPath();
90         }
91
92         addCellEditorListener(this);
93     }
94
95     /** Implements <code>CellEditorListener</code> interface method. */
96     public void editingStopped(ChangeEvent JavaDoc e) {
97         //CellEditor sometimes(probably after stopCellEditing() call) gains one focus but loses two
98
if (stopped) {
99             return;
100         }
101
102         stopped = true;
103
104         TreePath JavaDoc lastP = lastPath;
105
106         if (lastP != null) {
107             Node n = Visualizer.findNode(lastP.getLastPathComponent());
108
109             if ((n != null) && n.canRename()) {
110                 String JavaDoc newStr = (String JavaDoc) getCellEditorValue();
111
112                 try {
113                     // bugfix #21589 don't update name if there is not any change
114
if (!n.getName().equals(newStr)) {
115                         n.setName(newStr);
116                     }
117                 } catch (IllegalArgumentException JavaDoc exc) {
118                     boolean needToAnnotate = Exceptions.findLocalizedMessage(exc) == null;
119
120                     // annotate new localized message only if there is no localized message yet
121
if (needToAnnotate) {
122                         String JavaDoc msg = NbBundle.getMessage(TreeViewCellEditor.class, "RenameFailed", n.getName(), newStr);
123                         Exceptions.attachLocalizedMessage(exc, msg);
124                     }
125
126                     DialogDisplayer.getDefault().notifyLater(new NotifyDescriptor.Exception(exc));
127                 }
128             }
129         }
130     }
131
132     /** Implements <code>CellEditorListener</code> interface method. */
133     public void editingCanceled(ChangeEvent JavaDoc e) {
134         cancelled = true;
135     }
136
137     /** Overrides superclass method. If the source is a <code>JTextField</code>,
138      * i.e. cell editor, it cancels editing, otherwise it calls superclass method. */

139     public void actionPerformed(ActionEvent JavaDoc evt) {
140         if (evt.getSource() instanceof JTextField JavaDoc) {
141             cancelled = true;
142             cancelCellEditing();
143         } else {
144             super.actionPerformed(evt);
145         }
146     }
147
148     /** Implements <code>FocusListener</code> interface method. */
149     public void focusLost(FocusEvent JavaDoc evt) {
150         if (stopped || cancelled) {
151             return;
152         }
153
154         if (!stopCellEditing()) {
155             cancelCellEditing();
156         }
157     }
158
159     /** Dummy implementation of <code>FocusListener</code> interface method. */
160     public void focusGained(FocusEvent JavaDoc evt) {
161     }
162
163     /**
164      * This is invoked if a TreeCellEditor is not supplied in the constructor.
165      * It returns a TextField editor.
166      */

167     protected TreeCellEditor JavaDoc createTreeCellEditor() {
168         JTextField JavaDoc tf = new JTextField JavaDoc() {
169                 public void addNotify() {
170                     stopped = cancelled = false;
171                     super.addNotify();
172                     requestFocus();
173                 }
174             };
175
176         tf.registerKeyboardAction( //TODO update to use inputMap/actionMap
177
this, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), JComponent.WHEN_FOCUSED);
178
179         tf.addFocusListener(this);
180
181         Ed ed = new Ed(tf);
182         ed.setClickCountToStart(1);
183         ed.getComponent().getAccessibleContext().setAccessibleDescription(
184             NbBundle.getMessage(TreeViewCellEditor.class, "ACSD_TreeViewCellEditor")
185         ); // NOI18N
186
ed.getComponent().getAccessibleContext().setAccessibleName(
187             NbBundle.getMessage(TreeViewCellEditor.class, "ACSN_TreeViewCellEditor")
188         ); // NOI18N
189

190         return ed;
191     }
192
193     /*
194     * If the realEditor returns true to this message, prepareForEditing
195     * is messaged and true is returned.
196     */

197     public boolean isCellEditable(EventObject JavaDoc event) {
198         if ((event != null) && (event instanceof MouseEvent JavaDoc)) {
199             if (!SwingUtilities.isLeftMouseButton((MouseEvent JavaDoc) event) || ((MouseEvent JavaDoc) event).isPopupTrigger()) {
200                 return false;
201             }
202         }
203
204         if (lastPath != null) {
205             Node n = Visualizer.findNode(lastPath.getLastPathComponent());
206
207             if ((n == null) || !n.canRename()) {
208                 return false;
209             }
210         } else {
211             // Disallow rename when multiple nodes are selected
212
return false;
213         }
214
215         // disallow editing if we are in DnD operation
216
if (dndActive) {
217             return false;
218         }
219
220         return super.isCellEditable(event);
221     }
222
223     protected void determineOffset(JTree JavaDoc tree, Object JavaDoc value, boolean sel, boolean expanded, boolean leaf, int row) {
224         if (renderer != null) {
225             renderer.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, true);
226             editingIcon = renderer.getIcon();
227
228             if (editingIcon != null) {
229                 offset = renderer.getIconTextGap() + editingIcon.getIconWidth();
230             } else {
231                 offset = 0;
232             }
233         } else {
234             editingIcon = null;
235             offset = 0;
236         }
237     }
238
239     /*** Sets the state od drag and drop operation.
240     * It's here only because of JTree's bug which allows to
241     * start the editing even if DnD operation occurs
242     * (bug # )
243     */

244     void setDnDActive(boolean dndActive) {
245         if (!dndActive) {
246             tree.removeMouseMotionListener(this);
247         }
248
249         this.dndActive = dndActive;
250     }
251
252     protected void setTree(JTree JavaDoc newTree) {
253         if ((newTree != tree) && (timer != null) && timer.isRunning()) {
254             tree.removeMouseMotionListener(this);
255         }
256
257         super.setTree(newTree);
258     }
259
260     // bugfix #33765, cancel timer if the mouse leaves a selection rectangle
261
public void mouseDragged(MouseEvent JavaDoc e) {
262         Point JavaDoc p = e.getPoint();
263         boolean b = checkContinueTimer(p);
264
265         if (!b) {
266             abortTimer();
267         }
268     }
269
270     public void mouseMoved(MouseEvent JavaDoc e) {
271         Point JavaDoc p = e.getPoint();
272         boolean b = checkContinueTimer(p);
273
274         if (!b) {
275             abortTimer();
276         }
277     }
278
279     private void abortTimer() {
280         if ((timer != null) && timer.isRunning()) {
281             timer.stop();
282             tree.removeMouseMotionListener(this);
283         }
284     }
285
286     protected void startEditingTimer() {
287         tree.addMouseMotionListener(this);
288         super.startEditingTimer();
289     }
290
291     protected void prepareForEditing() {
292         abortTimer();
293         tree.removeMouseMotionListener(this);
294
295         super.prepareForEditing();
296     }
297
298     private boolean checkContinueTimer(Point JavaDoc p) {
299         Rectangle JavaDoc r = tree.getPathBounds(tree.getSelectionPath());
300
301         if (r == null) {
302             return false;
303         }
304
305         return (r.contains(p));
306     }
307
308     /** Redefined default cell editor to convert nodes to name */
309     class Ed extends DefaultCellEditor JavaDoc {
310         /** generated Serialized Version UID */
311         static final long serialVersionUID = -6373058702842751408L;
312
313         public Ed(JTextField JavaDoc tf) {
314             super(tf);
315         }
316
317         /** Main method of the editor.
318         * @return component of editor
319         */

320         public Component JavaDoc getTreeCellEditorComponent(
321             JTree JavaDoc tree, Object JavaDoc value, boolean isSelected, boolean expanded, boolean leaf, int row
322         ) {
323             Node ren = Visualizer.findNode(value);
324
325             if ((ren != null) && (ren.canRename())) {
326                 delegate.setValue(ren.getName());
327             } else {
328                 delegate.setValue(""); // NOI18N
329
}
330
331             editingIcon = ((VisualizerNode) value).getIcon(expanded, false);
332
333             ((JTextField JavaDoc) editorComponent).selectAll();
334
335             return editorComponent;
336         }
337     }
338 }
339
Popular Tags