KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > editor > imports > ImportClassPanel


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 package org.netbeans.modules.java.editor.imports;
21
22 import com.sun.source.tree.CompilationUnitTree;
23 import com.sun.source.tree.ImportTree;
24 import java.awt.Color JavaDoc;
25 import java.awt.Component JavaDoc;
26 import java.awt.Font JavaDoc;
27 import java.awt.event.KeyEvent JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.ListIterator JavaDoc;
34 import javax.lang.model.element.ElementKind;
35 import javax.lang.model.element.TypeElement;
36 import javax.swing.DefaultListCellRenderer JavaDoc;
37 import javax.swing.DefaultListModel JavaDoc;
38 import javax.swing.JLabel JavaDoc;
39 import javax.swing.JList JavaDoc;
40 import javax.swing.KeyStroke JavaDoc;
41 import org.netbeans.api.java.source.JavaSource;
42 import org.netbeans.api.java.source.CancellableTask;
43 import org.netbeans.api.java.source.JavaSource.Phase;
44 import org.netbeans.api.java.source.TreeMaker;
45 import org.netbeans.api.java.source.UiUtils;
46 import org.netbeans.api.java.source.WorkingCopy;
47 import org.netbeans.modules.java.editor.overridden.PopupUtil;
48 import org.openide.ErrorManager;
49
50 /**
51  *
52  * @author Jan Lahoda
53  */

54 public class ImportClassPanel extends javax.swing.JPanel JavaDoc {
55
56     private JavaSource javaSource;
57     private DefaultListModel JavaDoc model;
58     
59     /** Creates new form ImportClassPanel */
60     public ImportClassPanel(List JavaDoc<TypeElement> priviledged, List JavaDoc<TypeElement> denied, Font JavaDoc font, JavaSource javaSource ) {
61         // System.err.println("priviledged=" + priviledged);
62
// System.err.println("denied=" + denied);
63
this.javaSource = javaSource;
64         createModel(priviledged, denied);
65         initComponents();
66         setBackground(jList1.getBackground());
67         
68         if ( model.size() > 0) {
69             jList1.setModel( model );
70             setFocusable(false);
71             setNextFocusableComponent(jList1);
72             jScrollPane1.setBackground( jList1.getBackground() );
73             setBackground( jList1.getBackground() );
74             if ( font != null ) {
75                 jList1.setFont(font);
76             }
77             int modelSize = jList1.getModel().getSize();
78             if ( modelSize > 0 ) {
79                 jList1.setSelectedIndex(0);
80             }
81             jList1.setVisibleRowCount( modelSize > 8 ? 8 : modelSize );
82             jList1.setCellRenderer( new Renderer JavaDoc( jList1 ) );
83             jList1.grabFocus();
84         }
85         else {
86             remove( jScrollPane1 );
87             JLabel JavaDoc nothingFoundJL = new JLabel JavaDoc("<No Classes Found>");
88             if ( font != null ) {
89                 nothingFoundJL.setFont(font);
90             }
91             nothingFoundJL.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 4, 4, 4));
92             nothingFoundJL.setEnabled(false);
93             nothingFoundJL.setBackground(jList1.getBackground());
94             //nothingFoundJL.setOpaque(true);
95
add( nothingFoundJL );
96         }
97     }
98     
99     /** This method is called from within the constructor to
100      * initialize the form.
101      * WARNING: Do NOT modify this code. The content of this method is
102      * always regenerated by the Form Editor.
103      */

104     // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
105
private void initComponents() {
106
107         jScrollPane1 = new javax.swing.JScrollPane JavaDoc();
108         jList1 = new javax.swing.JList JavaDoc();
109         jLabel1 = new javax.swing.JLabel JavaDoc();
110
111         setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.darkGray));
112         setLayout(new java.awt.BorderLayout JavaDoc());
113
114         jScrollPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 4, 4, 4));
115
116         jList1.addKeyListener(new java.awt.event.KeyAdapter JavaDoc() {
117             public void keyReleased(java.awt.event.KeyEvent JavaDoc evt) {
118                 listKeyReleased(evt);
119             }
120         });
121         jList1.addMouseListener(new java.awt.event.MouseAdapter JavaDoc() {
122             public void mouseReleased(java.awt.event.MouseEvent JavaDoc evt) {
123                 listMouseReleased(evt);
124             }
125         });
126         jScrollPane1.setViewportView(jList1);
127
128         add(jScrollPane1, java.awt.BorderLayout.CENTER);
129
130         jLabel1.setText("Type to import:");
131         jLabel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
132         jLabel1.setOpaque(true);
133         add(jLabel1, java.awt.BorderLayout.PAGE_START);
134     }// </editor-fold>//GEN-END:initComponents
135

136     private void listMouseReleased(java.awt.event.MouseEvent JavaDoc evt) {//GEN-FIRST:event_listMouseReleased
137
importClass( getSelected() );
138     }//GEN-LAST:event_listMouseReleased
139

140     private void listKeyReleased(java.awt.event.KeyEvent JavaDoc evt) {//GEN-FIRST:event_listKeyReleased
141
KeyStroke JavaDoc ks = KeyStroke.getKeyStrokeForEvent(evt);
142         if ( ks.getKeyCode() == KeyEvent.VK_ENTER ||
143              ks.getKeyCode() == KeyEvent.VK_SPACE ) {
144             importClass( getSelected() );
145         }
146     }//GEN-LAST:event_listKeyReleased
147

148     
149     // Variables declaration - do not modify//GEN-BEGIN:variables
150
public javax.swing.JLabel JavaDoc jLabel1;
151     public javax.swing.JList JavaDoc jList1;
152     public javax.swing.JScrollPane JavaDoc jScrollPane1;
153     // End of variables declaration//GEN-END:variables
154

155     public String JavaDoc getSelected() {
156         TypeDescription typeDescription = ((TypeDescription)jList1.getSelectedValue());
157         return typeDescription == null ? null : typeDescription.qualifiedName;
158     }
159     
160     private void createModel( List JavaDoc<TypeElement> priviledged, List JavaDoc<TypeElement> denied ) {
161                 
162         List JavaDoc<TypeDescription> l = new ArrayList JavaDoc( priviledged.size() );
163         for (TypeElement typeElement : priviledged) {
164             l.add( new TypeDescription( typeElement, false ) );
165         }
166         
167         List JavaDoc<TypeDescription> ld = new ArrayList JavaDoc( priviledged.size() );
168         for (TypeElement typeElement : denied ) {
169             l.add( new TypeDescription( typeElement, true ) );
170         }
171         
172         Collections.sort( l );
173         
174         model = new DefaultListModel JavaDoc();
175         for( TypeDescription td : l ) {
176             model.addElement( td );
177         }
178         
179         
180         
181     }
182     
183     private void importClass( final String JavaDoc fqn ) {
184         PopupUtil.hidePopup();
185         
186         if (fqn != null) {
187             CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
188                 
189                 public void run(final WorkingCopy wc) throws IOException JavaDoc {
190                     wc.toPhase(Phase.RESOLVED);
191                     TreeMaker make = wc.getTreeMaker();
192                     CompilationUnitTree cut = wc.getCompilationUnit();
193                     // make a copy of list
194
List JavaDoc<ImportTree> imports = new ArrayList JavaDoc<ImportTree>(cut.getImports());
195                     // prepare the import tree to add
196
ImportTree njuImport = make.Import(make.Identifier(fqn), false);
197                     for (ListIterator JavaDoc<ImportTree> it = imports.listIterator(); it.hasNext(); ) {
198                         ImportTree item = it.next();
199                         if (item.isStatic() || item.getQualifiedIdentifier().toString().compareTo(fqn) > 0) {
200                             it.set(njuImport);
201                             it.add(item);
202                             break;
203                         }
204                     }
205                     CompilationUnitTree cutCopy;
206                     // import was inserted somewhere to inside the list, prepare
207
// copy of compilation unit.
208
if (imports.contains(njuImport)) {
209                         cutCopy = make.CompilationUnit(
210                             cut.getPackageName(),
211                             imports,
212                             cut.getTypeDecls(),
213                             cut.getSourceFile()
214                         );
215                     } else {
216                         // import section was not modified by for loop,
217
// either it means the section is empty or
218
// the import has to be added to the end of the section.
219
// prepare copy of compilation unit tree.
220
cutCopy = make.addCompUnitImport(cut, njuImport);
221                     }
222                     wc.rewrite(cut, cutCopy);
223                 }
224                 
225                 public void cancel() {
226                 }
227             };
228             try {
229                 javaSource.runModificationTask(task).commit();
230             } catch (IOException JavaDoc ex) {
231                 ErrorManager.getDefault().notify(ex);
232             }
233         }
234     }
235             
236     private static class Renderer extends DefaultListCellRenderer JavaDoc {
237         
238         private static int DARKER_COLOR_COMPONENT = 5;
239         private static int LIGHTER_COLOR_COMPONENT = DARKER_COLOR_COMPONENT;
240                 
241         
242         private Color JavaDoc denidedColor = new Color JavaDoc( 0x80, 0x80, 0x80 );
243         private Color JavaDoc fgColor;
244         private Color JavaDoc bgColor;
245         private Color JavaDoc bgColorDarker;
246         private Color JavaDoc bgSelectionColor;
247         private Color JavaDoc fgSelectionColor;
248         
249         public Renderer( JList JavaDoc list ) {
250             setFont( list.getFont() );
251             fgColor = list.getForeground();
252             bgColor = list.getBackground();
253             bgColorDarker = new Color JavaDoc(
254                                     Math.abs(bgColor.getRed() - DARKER_COLOR_COMPONENT),
255                                     Math.abs(bgColor.getGreen() - DARKER_COLOR_COMPONENT),
256                                     Math.abs(bgColor.getBlue() - DARKER_COLOR_COMPONENT)
257                             );
258             bgSelectionColor = list.getSelectionBackground();
259             fgSelectionColor = list.getSelectionForeground();
260         }
261         
262         public Component JavaDoc getListCellRendererComponent( JList JavaDoc list,
263                                                        Object JavaDoc value,
264                                                        int index,
265                                                        boolean isSelected,
266                                                        boolean hasFocus) {
267                         
268             if ( isSelected ) {
269                 setForeground(fgSelectionColor);
270                 setBackground(bgSelectionColor);
271             }
272             else {
273                 setForeground(fgColor);
274                 setBackground( index % 2 == 0 ? bgColor : bgColorDarker );
275             }
276             
277             if ( value instanceof TypeDescription ) {
278                 TypeDescription td = (TypeDescription)value;
279                  // setIcon(td.getIcon());
280
setText(td.qualifiedName);
281                 if ( td.isDenied ) {
282                     setForeground( denidedColor );
283                 }
284                 setIcon( UiUtils.getElementIcon( td.kind, null ) );
285             }
286             else {
287                 setText( value.toString() );
288             }
289                                     
290             return this;
291         }
292         
293      }
294      
295      private static class TypeDescription implements Comparable JavaDoc<TypeDescription> {
296          private boolean isDenied;
297          private final ElementKind kind;
298          private final String JavaDoc qualifiedName;
299                           
300          public TypeDescription(TypeElement typeElement, boolean isDenied ) {
301             this.isDenied = isDenied;
302             this.kind = typeElement.getKind();
303             this.qualifiedName = typeElement.getQualifiedName().toString();
304          }
305
306         public int compareTo( TypeDescription o ) {
307             
308             if ( isDenied && !o.isDenied ) {
309                 return 1;
310             }
311             else if ( !isDenied && o.isDenied ) {
312                 return -1;
313             }
314             else {
315                 return qualifiedName.compareTo( o.qualifiedName );
316             }
317         }
318          
319          
320          
321      }
322             
323
324 }
325
Popular Tags