KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > junit > JUnitCfgOfCreate


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-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.junit;
21
22 import java.awt.BorderLayout JavaDoc;
23 import java.awt.Color JavaDoc;
24 import java.awt.Component JavaDoc;
25 import java.awt.Container JavaDoc;
26 import java.awt.Font JavaDoc;
27 import java.awt.GridBagConstraints JavaDoc;
28 import java.awt.GridBagLayout JavaDoc;
29 import java.awt.Insets JavaDoc;
30 import java.awt.event.ActionListener JavaDoc;
31 import java.awt.event.ItemEvent JavaDoc;
32 import java.awt.event.ItemListener JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.ResourceBundle JavaDoc;
37 import java.util.Stack JavaDoc;
38 import javax.swing.BorderFactory JavaDoc;
39 import javax.swing.Box JavaDoc;
40 import javax.swing.BoxLayout JavaDoc;
41 import javax.swing.DefaultComboBoxModel JavaDoc;
42 import javax.swing.DefaultListCellRenderer JavaDoc;
43 import javax.swing.JButton JavaDoc;
44 import javax.swing.JCheckBox JavaDoc;
45 import javax.swing.JComboBox JavaDoc;
46 import javax.swing.JComponent JavaDoc;
47 import javax.swing.JLabel JavaDoc;
48 import javax.swing.JList JavaDoc;
49 import javax.swing.JPanel JavaDoc;
50 import javax.swing.JTextArea JavaDoc;
51 import javax.swing.ListCellRenderer JavaDoc;
52 import javax.swing.UIManager JavaDoc;
53 import javax.swing.border.Border JavaDoc;
54 import javax.swing.border.CompoundBorder JavaDoc;
55 import javax.swing.border.TitledBorder JavaDoc;
56 import javax.swing.event.ChangeEvent JavaDoc;
57 import javax.swing.event.ChangeListener JavaDoc;
58 import javax.swing.plaf.UIResource JavaDoc;
59 import org.netbeans.api.java.classpath.ClassPath;
60 import org.netbeans.api.project.SourceGroup;
61 import org.openide.DialogDescriptor;
62 import org.openide.DialogDisplayer;
63 import org.openide.awt.Mnemonics;
64 import org.openide.filesystems.FileObject;
65 import org.openide.filesystems.FileUtil;
66 import org.openide.loaders.DataFolder;
67 import org.openide.loaders.DataObject;
68 import org.openide.nodes.Node;
69 import org.openide.util.HelpCtx;
70 import org.openide.util.Lookup;
71 import org.openide.util.NbBundle;
72
73
74 /**
75  *
76  * @author vstejskal
77  * @author Marian Petras
78  */

79 public final class JUnitCfgOfCreate extends SelfResizingPanel
80                                     implements ChangeListener JavaDoc {
81     
82     /** suffix of test classes */
83     private static final String JavaDoc TEST_CLASS_SUFFIX = "Test"; //NOI18N
84

85     /**
86      * nodes selected when the Create Tests action was invoked
87      */

88     private final Node[] nodes;
89     /** whether the tests will be created for multiple classes */
90     private final boolean multipleClasses;
91     /** whether a single package/folder is selected */
92     private boolean singlePackage;
93     /** whether a single class is selected */
94     private boolean singleClass;
95     /** test class name specified in the form (or <code>null</code>) */
96     private String JavaDoc testClassName;
97     /** registered change listeners */
98     private List JavaDoc<ChangeListener JavaDoc> changeListeners;
99     /** */
100     private String JavaDoc initialMessage;
101     
102     /**
103      * is at least one target folder/source group available?
104      *
105      * @see #isAcceptable()
106      */

107     private boolean hasTargetFolders = false;
108
109     /**
110      * is combination of checkbox states acceptable?
111      *
112      * @see #isAcceptable()
113      */

114     private boolean checkBoxesOK;
115     
116     /**
117      * message about invalid configuration of checkboxes
118      * in the <em>Method Access Levels</em> group
119      */

120     private String JavaDoc msgChkBoxesInvalid;
121     
122     /**
123      * is the entered class name non-empty and valid?
124      *
125      * @see #isAcceptable()
126      */

127     private boolean classNameValid;
128     
129     /**
130      * is the current form contents acceptable?
131      *
132      * @see #isAcceptable()
133      */

134     private boolean isAcceptable;
135     
136     /** layer index for a message about an empty set of target folders */
137     private static final int MSG_TYPE_NO_TARGET_FOLDERS = 0;
138     /** layer index for a message about invalid configuration of checkboxes */
139     private static final int MSG_TYPE_INVALID_CHKBOXES = 1;
140     /** layer index for a message about invalid class name */
141     private static final int MSG_TYPE_CLASSNAME_INVALID = 2;
142     /** layer index for a message about non-default class name */
143     private static final int MSG_TYPE_CLASSNAME_NOT_DEFAULT = 3;
144     /** */
145     private MessageStack msgStack = new MessageStack(4);
146
147     /**
148      * Creates a JUnit configuration panel.
149      *
150      * @param nodes nodes selected when the Create Tests action was invoked
151      */

152     JUnitCfgOfCreate(Node[] nodes) {
153         assert (nodes != null) && (nodes.length != 0);
154         
155         this.nodes = nodes;
156         multipleClasses = checkMultipleClasses();
157         
158         initBundle();
159         try {
160             initComponents();
161             setBorder(BorderFactory.createEmptyBorder(12, 12, 0, 11));
162             addAccessibleDescriptions();
163             initializeCheckBoxStates();
164             fillFormData();
165             checkAcceptability();
166             setupUserInteraction();
167             
168             /*
169              * checkAcceptability() must not be called
170              * before initializeCheckBoxStates() and fillFormData()
171              * setupUserInteraction must not be called
172              * before initializeCheckBoxStates()
173              */

174             
175         } finally {
176             unlinkBundle();
177         }
178     }
179     
180     private void addAccessibleDescriptions() {
181         
182         // window
183
this.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.AD"));
184         
185         // text-field and combo-box
186

187         if (this.tfClassName != null) {
188             this.tfClassName.setToolTipText(
189                   bundle.getString("JUnitCfgOfCreate.clsName.toolTip"));//NOI18N
190
this.tfClassName.getAccessibleContext().setAccessibleName(
191                   bundle.getString("JUnitCfgOfCreate.clsName.AN")); //NOI18N
192
this.tfClassName.getAccessibleContext().setAccessibleDescription(
193                   bundle.getString("JUnitCfgOfCreate.clsName.AD")); //NOI18N
194
}
195         
196         this.cboxLocation.setToolTipText(
197                 bundle.getString("JUnitCfgOfCreate.location.toolTip")); //NOI18N
198
this.cboxLocation.getAccessibleContext().setAccessibleName(
199                 bundle.getString("JUnitCfgOfCreate.location.AN")); //NOI18N
200
this.cboxLocation.getAccessibleContext().setAccessibleDescription(
201                 bundle.getString("JUnitCfgOfCreate.location.AD")); //NOI18N
202

203         // check boxes
204
this.chkPublic.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkPublic.toolTip"));
205         this.chkPublic.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkPublic.AD"));
206         
207         this.chkProtected.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkProtected.toolTip"));
208         this.chkProtected.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkProtected.AD"));
209         
210         this.chkPackage.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkPackage.toolTip"));
211         this.chkPackage.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkPackage.AD"));
212         
213         this.chkComments.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkComments.toolTip"));
214         this.chkComments.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkComments.AD"));
215         
216         this.chkContent.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkContent.toolTip"));
217         this.chkContent.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkContent.AD"));
218         
219         this.chkJavaDoc.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkJavaDoc.toolTip"));
220         this.chkJavaDoc.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkJavaDoc.AD"));
221         
222         if (multipleClasses) {
223             this.chkExceptions.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkExceptions.toolTip"));
224             this.chkExceptions.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkExceptions.AD"));
225         
226             this.chkAbstractImpl.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkAbstractImpl.toolTip"));
227             this.chkAbstractImpl.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkAbstractImpl.AD"));
228         
229             this.chkPackagePrivateClasses.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkPackagePrivateClasses.toolTip"));
230             this.chkPackagePrivateClasses.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkPackagePrivateClasses.AD"));
231         
232             this.chkGenerateSuites.setToolTipText(bundle.getString("JUnitCfgOfCreate.chkGenerateSuites.toolTip"));
233             this.chkGenerateSuites.getAccessibleContext().setAccessibleDescription(bundle.getString("JUnitCfgOfCreate.chkGenerateSuites.AD"));
234         }
235         
236     }
237     
238     /**
239      * Checks whether multiple classes may be selected.
240      * It also detects whether exactly one package/folder or exactly one class
241      * is selected and sets values of variables {@link #singlePackage}
242      * and {@link #singleClass} accordingly.
243      *
244      * @return <code>false</code> if there is exactly one node selected
245      * and the node represents a single <code>DataObject</code>,
246      * not a folder or another <code>DataObject</code> container;
247      * <code>true</code> otherwise
248      */

249     private boolean checkMultipleClasses() {
250         if (nodes.length > 1) {
251             return true;
252         }
253         
254         Lookup nodeLookup = nodes[0].getLookup();
255         if (nodeLookup.lookup(DataObject.Container.class) != null) {
256             singlePackage = nodeLookup.lookup(DataFolder.class)
257                             != null;
258             return true;
259         }
260         
261         singleClass = false;
262         DataObject dataObj = nodeLookup.lookup(DataObject.class);
263         if (dataObj == null) {
264             return true;
265         }
266         
267         singleClass = dataObj.getPrimaryFile().isData();
268         return !singleClass;
269     }
270     
271     /**
272      * Displays a configuration dialog and updates JUnit options according
273      * to the user's settings.
274      *
275      * @param nodes nodes selected when the Create Test action was invoked
276      */

277     boolean configure() {
278         
279         // create and display the dialog:
280
String JavaDoc title = NbBundle.getMessage(JUnitCfgOfCreate.class,
281                                            "JUnitCfgOfCreate.Title"); //NOI18N
282
ChangeListener JavaDoc changeListener;
283         final JButton JavaDoc btnOK = new JButton JavaDoc(
284                 NbBundle.getMessage(JUnitCfgOfCreate.class, "LBL_OK")); //NOI18N
285
btnOK.setEnabled(isAcceptable());
286         addChangeListener(changeListener = new ChangeListener JavaDoc() {
287             public void stateChanged(ChangeEvent JavaDoc e) {
288                 btnOK.setEnabled(isAcceptable());
289             }
290         });
291         
292         Object JavaDoc returned = DialogDisplayer.getDefault().notify(
293                 new DialogDescriptor (
294                         this,
295                         title,
296                         true, //modal
297
new Object JavaDoc[] {btnOK, DialogDescriptor.CANCEL_OPTION},
298                         btnOK, //initial value
299
DialogDescriptor.DEFAULT_ALIGN,
300                         new HelpCtx(JUnitCfgOfCreate.class),
301                         (ActionListener JavaDoc) null
302                 ));
303         removeChangeListener(changeListener);
304         
305         if (returned == btnOK) {
306             rememberCheckBoxStates();
307             testClassName = (tfClassName != null) ? tfClassName.getText()
308                                                   : null;
309             return true;
310         }
311         return false;
312     }
313     
314     /**
315      * Returns whether a test for a single class is to be created.
316      *
317      * @return true if there is only one node selected and the node
318      * represents a class
319      */

320     boolean isSingleClass() {
321         return singleClass;
322     }
323     
324     /**
325      * Returns the class name entered in the text-field.
326      *
327      * @return class name entered in the form,
328      * or <code>null</code> if the form did not contain
329      * the field for entering class name
330      */

331     String JavaDoc getTestClassName() {
332         return testClassName;
333     }
334     
335     /** resource bundle used during initialization of this panel */
336     public ResourceBundle JavaDoc bundle;
337     
338     /**
339      * Reads JUnit settings and initializes checkboxes accordingly.
340      *
341      * @see #rememberCheckBoxStates
342      */

343     private void initializeCheckBoxStates() {
344         final JUnitSettings settings = JUnitSettings.getDefault();
345         
346         chkPublic.setSelected(settings.isMembersPublic());
347         chkProtected.setSelected(settings.isMembersProtected());
348         chkPackage.setSelected(settings.isMembersPackage());
349         chkComments.setSelected(settings.isBodyComments());
350         chkContent.setSelected(settings.isBodyContent());
351         chkJavaDoc.setSelected(settings.isJavaDoc());
352         if (multipleClasses) {
353             chkGenerateSuites.setSelected(settings.isGenerateSuiteClasses());
354             chkPackagePrivateClasses.setSelected(
355                     settings.isIncludePackagePrivateClasses());
356             chkAbstractImpl.setSelected(settings.isGenerateAbstractImpl());
357             chkExceptions.setSelected(settings.isGenerateExceptionClasses());
358         }
359         chkSetUp.setSelected(settings.isGenerateSetUp());
360         chkTearDown.setSelected(settings.isGenerateTearDown());
361         
362         checkChkBoxesStates();
363     }
364     
365     /**
366      * Stores settings given by checkbox states to JUnit settings.
367      *
368      * @see #initializeCheckBoxStatesf
369      */

370     private void rememberCheckBoxStates() {
371         final JUnitSettings settings = JUnitSettings.getDefault();
372         
373         settings.setMembersPublic(chkPublic.isSelected());
374         settings.setMembersProtected(chkProtected.isSelected());
375         settings.setMembersPackage(chkPackage.isSelected());
376         settings.setBodyComments(chkComments.isSelected());
377         settings.setBodyContent(chkContent.isSelected());
378         settings.setJavaDoc(chkJavaDoc.isSelected());
379         if (multipleClasses) {
380             settings.setGenerateSuiteClasses(chkGenerateSuites.isSelected());
381             settings.setIncludePackagePrivateClasses(
382                     chkPackagePrivateClasses.isSelected());
383             settings.setGenerateAbstractImpl(chkAbstractImpl.isSelected());
384             settings.setGenerateExceptionClasses(chkExceptions.isSelected());
385         }
386         settings.setGenerateSetUp(chkSetUp.isSelected());
387         settings.setGenerateTearDown(chkTearDown.isSelected());
388     }
389     
390     /**
391      * Loads a resource bundle so that it can be used during intialization
392      * of this panel.
393      *
394      * @see #unlinkBundle
395      */

396     private void initBundle() {
397         bundle = NbBundle.getBundle(JUnitCfgOfCreate.class);
398     }
399     
400     /**
401      * Nulls the resource bundle so that it is not held in memory when it is
402      * not used.
403      *
404      * @see #initBundle
405      */

406     private void unlinkBundle() {
407         bundle = null;
408     }
409     
410     /**
411      * This method is called from within the constructor to initialize the form.
412      */

413     private void initComponents() {
414         setLayout(new BorderLayout JavaDoc(0, 12));
415         
416         add(createNameAndLocationPanel(), BorderLayout.NORTH);
417         add(createMessagePanel(), BorderLayout.CENTER);
418         add(createCodeGenPanel(), BorderLayout.SOUTH);
419     }
420     
421     /**
422      */

423     private void setupUserInteraction() {
424         final ItemListener JavaDoc listener = new CheckBoxListener();
425
426         chkPublic.addItemListener(listener);
427         chkProtected.addItemListener(listener);
428         chkPackage.addItemListener(listener);
429     }
430     
431     /**
432      */

433     private void checkChkBoxesStates() {
434         checkBoxesOK = chkPublic.isSelected()
435                        || chkProtected.isSelected()
436                        || chkPackage.isSelected();
437         if (checkBoxesOK) {
438             setMessage(null, MSG_TYPE_INVALID_CHKBOXES);
439         } else {
440             if (msgChkBoxesInvalid == null) {
441                 //PENDING - text of the message:
442
msgChkBoxesInvalid = NbBundle.getMessage(
443                         JUnitCfgOfCreate.class,
444                         "MSG_AllMethodTypesDisabled"); //NOI18N
445
}
446             setMessage(msgChkBoxesInvalid, MSG_TYPE_INVALID_CHKBOXES);
447         }
448     }
449     
450     /**
451      * Listener object that listens on state changes of some check-boxes.
452      */

453     private final class CheckBoxListener implements ItemListener JavaDoc {
454         public CheckBoxListener () {}
455         
456         public void itemStateChanged(ItemEvent JavaDoc e) {
457             final Object JavaDoc source = e.getSource();
458             
459             assert source == chkPublic
460                    || source == chkProtected
461                    || source == chkPackage;
462             checkChkBoxesStates();
463             checkAcceptability();
464         }
465         
466     }
467     
468     /**
469      */

470     private Component JavaDoc createNameAndLocationPanel() {
471         JPanel JavaDoc panel = new JPanel JavaDoc();
472         
473         final boolean askForClassName = singleClass;
474         
475         JLabel JavaDoc lblClassToTest = new JLabel JavaDoc();
476         JLabel JavaDoc lblClassName = askForClassName ? new JLabel JavaDoc() : null;
477         JLabel JavaDoc lblLocation = new JLabel JavaDoc();
478         
479         String JavaDoc classToTestKey = singlePackage
480                                 ? "LBL_PackageToTest" //NOI18N
481
: singleClass
482                                   ? "LBL_ClassToTest" //NOI18N
483
: "LBL_MultipleClassesSelected"; //NOI18N
484

485         Mnemonics.setLocalizedText(
486                 lblClassToTest,
487                 NbBundle.getMessage(getClass(), classToTestKey));
488         if (askForClassName) {
489             Mnemonics.setLocalizedText(
490                     lblClassName,
491                     NbBundle.getMessage(getClass(), "LBL_ClassName")); //NOI18N
492
}
493         Mnemonics.setLocalizedText(
494                 lblLocation,
495                 NbBundle.getMessage(getClass(), "LBL_Location")); //NOI18N
496

497         if (singlePackage || singleClass) {
498             lblClassToTestValue = new JLabel JavaDoc();
499         }
500         if (askForClassName) {
501             tfClassName = new ClassNameTextField();
502             tfClassName.setChangeListener(this);
503         }
504         cboxLocation = new JComboBox JavaDoc();
505         
506         if (askForClassName) {
507             lblClassName.setLabelFor(tfClassName);
508         }
509         lblLocation.setLabelFor(cboxLocation);
510         
511         if (lblClassToTestValue != null) {
512             Font JavaDoc labelFont = javax.swing.UIManager.getDefaults()
513                              .getFont("TextField.font"); //NOI18N
514
if (labelFont != null) {
515                 lblClassToTestValue.setFont(labelFont);
516             }
517         }
518         
519         panel.setLayout(new GridBagLayout JavaDoc());
520         
521         GridBagConstraints JavaDoc gbcLeft = new GridBagConstraints JavaDoc();
522         gbcLeft.anchor = GridBagConstraints.WEST;
523         gbcLeft.insets.bottom = 12;
524         gbcLeft.insets.right = 6;
525         
526         GridBagConstraints JavaDoc gbcRight = new GridBagConstraints JavaDoc();
527         gbcRight.anchor = GridBagConstraints.WEST;
528         gbcRight.insets.bottom = 12;
529         gbcRight.weightx = 1.0f;
530         gbcRight.fill = GridBagConstraints.BOTH;
531         gbcRight.gridwidth = GridBagConstraints.REMAINDER;
532         
533         if (lblClassToTestValue != null) {
534             panel.add(lblClassToTest, gbcLeft);
535             panel.add(lblClassToTestValue, gbcRight);
536         } else {
537             panel.add(lblClassToTest, gbcRight);
538         }
539         if (askForClassName) {
540             panel.add(lblClassName, gbcLeft);
541             panel.add(tfClassName, gbcRight);
542         }
543         gbcLeft.insets.bottom = 0;
544         gbcRight.insets.bottom = 0;
545         panel.add(lblLocation, gbcLeft);
546         panel.add(cboxLocation, gbcRight);
547         
548         return panel;
549     }
550     
551     /**
552      */

553     private void checkClassNameValidity() {
554         if (tfClassName == null) {
555             classNameValid = true;
556             return;
557         }
558         
559         String JavaDoc key = null;
560         final int state = tfClassName.getStatus();
561         switch (state) {
562             case ClassNameTextField.STATUS_EMPTY:
563                 //PENDING - polish the message:
564
key = "MSG_ClassnameMustNotBeEmpty"; //NOI18N
565
break;
566             case ClassNameTextField.STATUS_INVALID:
567                 //PENDING - polish the message:
568
key = "MSG_InvalidClassName"; //NOI18N
569
break;
570             case ClassNameTextField.STATUS_VALID_NOT_DEFAULT:
571                 //PENDING - polish the message:
572
key = "MSG_ClassNameNotDefault"; //NOI18N
573
break;
574         }
575         if (state != ClassNameTextField.STATUS_VALID_NOT_DEFAULT) {
576             setMessage(null, MSG_TYPE_CLASSNAME_NOT_DEFAULT);
577         }
578         setMessage((key != null)
579                            ? NbBundle.getMessage(getClass(), key)
580                            : null,
581                    MSG_TYPE_CLASSNAME_INVALID);
582         
583         classNameValid =
584                 (state == ClassNameTextField.STATUS_VALID)
585                 || (state == ClassNameTextField.STATUS_VALID_NOT_DEFAULT);
586     }
587     
588     /**
589      * This method gets called if status of contents of the Class Name
590      * text field changes. See <code>STATUS_xxx</code> constants
591      * in class <code>ClassNameTextField</code>.
592      *
593      * @param e event describing the state change event
594      * (unused in this method)
595      */

596     public void stateChanged(ChangeEvent JavaDoc e) {
597         checkClassNameValidity();
598         checkAcceptability();
599     }
600     
601     /**
602      */

603     private void checkAcceptability() {
604         final boolean wasAcceptable = isAcceptable;
605         isAcceptable = hasTargetFolders && classNameValid && checkBoxesOK;
606         if (isAcceptable != wasAcceptable) {
607             fireStateChange();
608         }
609     }
610     
611     /**
612      * Are the values filled in the form acceptable?
613      *
614      * @see #addChangeListener
615      */

616     private boolean isAcceptable() {
617         return isAcceptable;
618     }
619     
620     /**
621      * This method is called the first time this panel's children are painted.
622      * By default, this method just calls {@link #adjustWindowSize()}.
623      *
624      * @param g <code>Graphics</code> used to paint this panel's children
625      */

626     protected void paintedFirstTime(java.awt.Graphics JavaDoc g) {
627         if (initialMessage != null) {
628             displayMessage(initialMessage);
629             initialMessage = null;
630         }
631     }
632     
633     /**
634      * Displays a given message in the message panel and resizes the dialog
635      * if necessary. If the message cannot be displayed immediately,
636      * because of this panel not displayed (painted) yet, displaying the message
637      * is deferred until this panel is painted.
638      *
639      * @param message message to be displayed, or <code>null</code> if
640      * the currently displayed message (if any) should be
641      * removed
642      */

643     private void setMessage(final String JavaDoc message, final int msgType) {
644         String JavaDoc msgToDisplay = msgStack.setMessage(msgType, message);
645         if (msgToDisplay == null) {
646             return; //no change
647
}
648
649         /* display the message: */
650         if (!isPainted()) {
651             initialMessage = msgToDisplay;
652         } else {
653             displayMessage(msgToDisplay);
654         }
655     }
656     
657     /**
658      * Displays a given message in the message panel and resizes the dialog
659      * if necessary.
660      *
661      * @param message message to be displayed, or <code>null</code> if
662      * the currently displayed message (if any) should be
663      * removed
664      * @see #adjustWindowSize()
665      */

666     private void displayMessage(String JavaDoc message) {
667         if (message == null) {
668             message = ""; //NOI18N
669
}
670         
671         txtAreaMessage.setText(message);
672         adjustWindowSize();
673     }
674     
675     /**
676      */

677     private Component JavaDoc createMessagePanel() {
678         txtAreaMessage = (JTextArea JavaDoc) GuiUtils.createMultilineLabel(""); //NOI18N
679

680         Color JavaDoc color = UIManager.getColor("nb.errorForeground"); //NOI18N
681
if (color == null) {
682             color = new Color JavaDoc(89, 79, 191); //RGB suggested by Bruce in #28466
683
}
684         txtAreaMessage.setForeground(color);
685
686         return txtAreaMessage;
687     }
688     
689     /**
690      * Creates a panel containing controls for settings code generation options.
691      *
692      * @return created panel
693      */

694     private Component JavaDoc createCodeGenPanel() {
695         
696         /* create the components: */
697         String JavaDoc[] chkBoxIDs;
698         JCheckBox JavaDoc[] chkBoxes;
699         if (multipleClasses) {
700             chkBoxIDs = new String JavaDoc[] {
701                 GuiUtils.CHK_PUBLIC,
702                 GuiUtils.CHK_PROTECTED,
703                 GuiUtils.CHK_PACKAGE,
704                 GuiUtils.CHK_PACKAGE_PRIVATE_CLASSES,
705                 GuiUtils.CHK_ABSTRACT_CLASSES,
706                 GuiUtils.CHK_EXCEPTION_CLASSES,
707                 GuiUtils.CHK_SUITES,
708                 GuiUtils.CHK_SETUP,
709                 GuiUtils.CHK_TEARDOWN,
710                 GuiUtils.CHK_METHOD_BODIES,
711                 GuiUtils.CHK_JAVADOC,
712                 GuiUtils.CHK_HINTS
713             };
714         } else {
715             chkBoxIDs = new String JavaDoc[] {
716                 GuiUtils.CHK_PUBLIC,
717                 GuiUtils.CHK_PROTECTED,
718                 GuiUtils.CHK_PACKAGE,
719                 null, // CHK_PACKAGE_PRIVATE_CLASSES,
720
null, // CHK_ABSTRACT_CLASSES,
721
null, // CHK_EXCEPTION_CLASSES,
722
null, // CHK_SUITES,
723
GuiUtils.CHK_SETUP,
724                 GuiUtils.CHK_TEARDOWN,
725                 GuiUtils.CHK_METHOD_BODIES,
726                 GuiUtils.CHK_JAVADOC,
727                 GuiUtils.CHK_HINTS
728             };
729         }
730         chkBoxes = GuiUtils.createCheckBoxes(chkBoxIDs);
731         int i = 0;
732         chkPublic = chkBoxes[i++];
733         chkProtected = chkBoxes[i++];
734         chkPackage = chkBoxes[i++];
735         chkPackagePrivateClasses = chkBoxes[i++]; //may be null
736
chkAbstractImpl = chkBoxes[i++]; //may be null
737
chkExceptions = chkBoxes[i++]; //may be null
738
chkGenerateSuites = chkBoxes[i++]; //may be null
739
chkSetUp = chkBoxes[i++];
740         chkTearDown = chkBoxes[i++];
741         chkContent = chkBoxes[i++];
742         chkJavaDoc = chkBoxes[i++];
743         chkComments = chkBoxes[i++];
744         
745         /* create groups of checkboxes: */
746         JComponent JavaDoc methodAccessLevels = GuiUtils.createChkBoxGroup(
747                 bundle.getString("JUnitCfgOfCreate.groupAccessLevels"), //NOI18N
748
new JCheckBox JavaDoc[] {chkPublic, chkProtected, chkPackage});
749         JComponent JavaDoc classTypes = null;
750         JComponent JavaDoc optionalClasses = null;
751         if (multipleClasses) {
752             classTypes = GuiUtils.createChkBoxGroup(
753                 bundle.getString("JUnitCfgOfCreate.groupClassTypes"), //NOI18N
754
new JCheckBox JavaDoc[] {chkPackagePrivateClasses,
755                                  chkAbstractImpl, chkExceptions});
756             optionalClasses = GuiUtils.createChkBoxGroup(
757                 bundle.getString("JUnitCfgOfCreate.groupOptClasses"), //NOI18N
758
new JCheckBox JavaDoc[] {chkGenerateSuites});
759         }
760         JComponent JavaDoc optionalCode = GuiUtils.createChkBoxGroup(
761                 bundle.getString("JUnitCfgOfCreate.groupOptCode"), //NOI18N
762
new JCheckBox JavaDoc[] {chkSetUp, chkTearDown, chkContent});
763         JComponent JavaDoc optionalComments = GuiUtils.createChkBoxGroup(
764                 bundle.getString("JUnitCfgOfCreate.groupOptComments"), //NOI18N
765
new JCheckBox JavaDoc[] {chkJavaDoc, chkComments});
766         
767         /* create the left column of options: */
768         Box JavaDoc leftColumn = Box.createVerticalBox();
769         leftColumn.add(methodAccessLevels);
770         if (multipleClasses) {
771             leftColumn.add(Box.createVerticalStrut(11));
772             leftColumn.add(classTypes);
773         } else {
774             /*
775              * This strut ensures that width of the left column is not limited.
776              * If it was limited, the rigth column would not move when the
777              * dialog is horizontally resized.
778              */

779             leftColumn.add(Box.createVerticalStrut(0));
780         }
781         leftColumn.add(Box.createVerticalGlue());
782         
783         /* create the right column of options: */
784         Box JavaDoc rightColumn = Box.createVerticalBox();
785         if (multipleClasses) {
786             rightColumn.add(optionalClasses);
787             rightColumn.add(Box.createVerticalStrut(11));
788         }
789         rightColumn.add(optionalCode);
790         rightColumn.add(Box.createVerticalStrut(11));
791         rightColumn.add(optionalComments);
792         rightColumn.add(Box.createVerticalGlue());
793         
794         /* compose the final panel: */
795         //JPanel jpCodeGen = new SizeRestrictedPanel(false, true);
796
JPanel JavaDoc jpCodeGen = new JPanel JavaDoc();
797         jpCodeGen.setLayout(new BoxLayout JavaDoc(jpCodeGen, BoxLayout.X_AXIS));
798         jpCodeGen.add(leftColumn);
799         jpCodeGen.add(Box.createHorizontalStrut(24));
800         jpCodeGen.add(rightColumn);
801         
802         /* decorate the panel: */
803         addTitledBorder(jpCodeGen,
804                   new Insets JavaDoc(12, 12, 11, 12),
805                   bundle.getString("JUnitCfgOfCreate.jpCodeGen.title"));//NOI18N
806

807         /* tune the layout: */
808         methodAccessLevels.setAlignmentX(0.0f);
809         if (multipleClasses) {
810             classTypes.setAlignmentX(0.0f);
811             optionalClasses.setAlignmentX(0.0f);
812         }
813         optionalCode.setAlignmentX(0.0f);
814         optionalComments.setAlignmentX(0.0f);
815         
816         return jpCodeGen;
817     }
818     
819     /**
820      * Adds a border and a title around a given component.
821      * If the component already has some border, it is overridden (not kept).
822      *
823      * @param component component the border and title should be added to
824      * @param insets insets between the component and the titled border
825      * @param title text of the title
826      */

827     private static void addTitledBorder(JComponent JavaDoc component,
828                                         Insets JavaDoc insets,
829                                         String JavaDoc title) {
830         Border JavaDoc insideBorder = BorderFactory.createEmptyBorder(
831                 insets.top, insets.left, insets.bottom, insets.right);
832         Border JavaDoc outsideBorder = new TitledBorder JavaDoc(
833                 BorderFactory.createEtchedBorder(), title);
834         component.setBorder(new CompoundBorder JavaDoc(outsideBorder, insideBorder));
835     }
836     
837     /**
838      */

839     FileObject getTargetFolder() {
840         Object JavaDoc selectedLocation = cboxLocation.getSelectedItem();
841         
842         if (selectedLocation == null) {
843             return null;
844         }
845         
846         if (selectedLocation instanceof SourceGroup) {
847             return ((SourceGroup) selectedLocation).getRootFolder();
848         }
849         assert selectedLocation instanceof FileObject; //root folder
850
return (FileObject) selectedLocation;
851     }
852     
853     /**
854      * Initializes form in the Test Settings panel of the dialog.
855      */

856     private void fillFormData() {
857         final DataObject dataObj = (DataObject)
858                                   nodes[0].getLookup().lookup(DataObject.class);
859         final FileObject fileObj = dataObj.getPrimaryFile();
860         
861         if (singleClass) {
862             assert nodes.length == 1;
863             
864             ClassPath cp = ClassPath.getClassPath(fileObj, ClassPath.SOURCE);
865             String JavaDoc className = cp.getResourceName(fileObj, '.', false);
866             lblClassToTestValue.setText(className);
867             
868             if (tfClassName != null) {
869                 String JavaDoc prefilledName = className + TEST_CLASS_SUFFIX;
870                 tfClassName.setText(prefilledName);
871                 tfClassName.setDefaultText(prefilledName);
872                 tfClassName.setCaretPosition(prefilledName.length());
873             }
874         } else if (singlePackage) {
875             assert nodes.length == 1;
876             
877             ClassPath cp = ClassPath.getClassPath(fileObj, ClassPath.SOURCE);
878             String JavaDoc packageName = cp.getResourceName(fileObj, '.', true);
879             if (packageName.length() == 0) {
880                 packageName = NbBundle.getMessage(
881                         getClass(),
882                         "DefaultPackageName"); //NOI18N
883
}
884             lblClassToTestValue.setText(packageName);
885         } else {
886             //PENDING
887
}
888         
889         setupLocationChooser(fileObj);
890         
891         checkClassNameValidity();
892     }
893     
894     /**
895      */

896     private void setupLocationChooser(FileObject refFileObject) {
897         Object JavaDoc[] targetFolders = TestUtil.getTestTargets(refFileObject);
898         if (targetFolders.length != 0) {
899             hasTargetFolders = true;
900             cboxLocation.setModel(new DefaultComboBoxModel JavaDoc(targetFolders));
901             cboxLocation.setRenderer(new LocationChooserRenderer());
902         } else {
903             hasTargetFolders = false;
904             //PENDING - message text:
905
String JavaDoc msgNoTargetsFound = NbBundle.getMessage(
906                                         getClass(),
907                                         refFileObject.isFolder()
908                                                 ? "MSG_NoTestTarget_Fo" //NOI18N
909
: "MSG_NoTestTarget_Fi",//NOI18N
910
refFileObject.getNameExt());
911             setMessage(msgNoTargetsFound, MSG_TYPE_NO_TARGET_FOLDERS);
912             disableComponents();
913         }
914     }
915     
916     /**
917      * Renderer which specially handles values of type
918      * <code>SourceGroup</code> and <code>FileObject</code>.
919      * It displays display names of these objects, instead of their default
920      * string representation (<code>toString()</code>).
921      *
922      * @see SourceGroup#getDisplayName()
923      * @see FileUtil#getFileDisplayName(FileObject)
924      */

925     private final class LocationChooserRenderer extends JLabel JavaDoc implements ListCellRenderer JavaDoc, UIResource JavaDoc {
926         
927         public LocationChooserRenderer () {
928             setOpaque(true);
929         }
930         
931         public Component JavaDoc getListCellRendererComponent(
932                 JList JavaDoc list,
933                 Object JavaDoc value,
934                 int index,
935                 boolean isSelected,
936                 boolean cellHasFocus) {
937             // #93658: GTK needs name to render cell renderer "natively"
938
setName("ComboBox.listRenderer"); // NOI18N
939

940             String JavaDoc text = value instanceof SourceGroup
941                         ? ((SourceGroup) value).getDisplayName()
942                         : value instanceof FileObject
943                               ? FileUtil.getFileDisplayName((FileObject) value)
944                               : value.toString();
945             setText(text);
946             
947             if ( isSelected ) {
948                 setBackground(list.getSelectionBackground());
949                 setForeground(list.getSelectionForeground());
950             }
951             else {
952                 setBackground(list.getBackground());
953                 setForeground(list.getForeground());
954             }
955             
956             return this;
957         }
958         
959         // #93658: GTK needs name to render cell renderer "natively"
960
public String JavaDoc getName() {
961             String JavaDoc name = super.getName();
962             return name == null ? "ComboBox.renderer" : name; // NOI18N
963
}
964             
965     }
966
967     /**
968      * Registers a change listener.
969      * Registered change listeners are notified when acceptability
970      * of values in the form changes.
971      *
972      * @param l listener to be registered
973      * @see #isAcceptable
974      * @see #removeChangeListener
975      */

976     private void addChangeListener(ChangeListener JavaDoc l) {
977         if (changeListeners == null) {
978             changeListeners = new ArrayList JavaDoc<ChangeListener JavaDoc>(3);
979         }
980         changeListeners.add(l);
981     }
982     
983     /**
984      * Unregisters the given change listener.
985      * If the given listener has not been registered before, calling this
986      * method does not have any effect.
987      *
988      * @param l change listener to be removed
989      * @see #addChangeListener
990      */

991     private void removeChangeListener(ChangeListener JavaDoc l) {
992         if (changeListeners != null
993                 && changeListeners.remove(l)
994                 && changeListeners.isEmpty()) {
995             changeListeners = null;
996         }
997     }
998     
999     /**
1000     * Notifies all registered change listeners about a change.
1001     *
1002     * @see #addChangeListener
1003     */

1004    private void fireStateChange() {
1005        if (changeListeners != null) {
1006            ChangeEvent JavaDoc e = new ChangeEvent JavaDoc(this);
1007            for (Iterator JavaDoc i = changeListeners.iterator(); i.hasNext(); ) {
1008                ((ChangeListener JavaDoc) i.next()).stateChanged(e);
1009            }
1010        }
1011    }
1012    
1013    /**
1014     * Disables all interactive visual components of this dialog
1015     * except the OK, Cancel and Help buttons.
1016     */

1017    private void disableComponents() {
1018        final Stack JavaDoc<Container JavaDoc> stack = new Stack JavaDoc<Container JavaDoc>();
1019        stack.push(this);
1020        
1021        while (!stack.empty()) {
1022            Container JavaDoc container = stack.pop();
1023            Component JavaDoc comps[] = container.getComponents();
1024            for (int i = 0; i < comps.length; i++) {
1025                final java.awt.Component JavaDoc comp = comps[i];
1026                
1027                if (comp == txtAreaMessage) {
1028                    continue;
1029                }
1030                if (comp instanceof JPanel JavaDoc) {
1031                    JPanel JavaDoc panel = (JPanel JavaDoc) comp;
1032                    stack.push(panel);
1033
1034                    final Border JavaDoc border = panel.getBorder();
1035                    if (border != null) {
1036                        disableBorderTitles(border);
1037                    }
1038                    continue;
1039                }
1040                comp.setEnabled(false);
1041                if (comp instanceof java.awt.Container JavaDoc) {
1042                    Container JavaDoc nestedCont = (Container JavaDoc) comp;
1043                    if (nestedCont.getComponentCount() != 0) {
1044                        stack.push(nestedCont);
1045                    }
1046                }
1047            }
1048        }
1049    }
1050    
1051    /**
1052     */

1053    private static void disableBorderTitles(Border JavaDoc border) {
1054        
1055        if (border instanceof TitledBorder JavaDoc) {
1056            disableBorderTitle((TitledBorder JavaDoc) border);
1057            return;
1058        }
1059        
1060        if (!(border instanceof CompoundBorder JavaDoc)) {
1061            return;
1062        }
1063        
1064        Stack JavaDoc<CompoundBorder JavaDoc> stack = new Stack JavaDoc<CompoundBorder JavaDoc>();
1065        stack.push((CompoundBorder JavaDoc) border);
1066        while (!stack.empty()) {
1067            CompoundBorder JavaDoc cb = stack.pop();
1068            
1069            Border JavaDoc b;
1070            b = cb.getOutsideBorder();
1071            if (b instanceof CompoundBorder JavaDoc) {
1072                stack.push((CompoundBorder JavaDoc) b);
1073            } else if (b instanceof TitledBorder JavaDoc) {
1074                disableBorderTitle((TitledBorder JavaDoc) b);
1075            }
1076            
1077            b = cb.getInsideBorder();
1078            if (b instanceof CompoundBorder JavaDoc) {
1079                stack.push((CompoundBorder JavaDoc) b);
1080            } else if (b instanceof TitledBorder JavaDoc) {
1081                disableBorderTitle((TitledBorder JavaDoc) b);
1082            }
1083        }
1084    }
1085    
1086    /**
1087     */

1088    private static void disableBorderTitle(TitledBorder JavaDoc border) {
1089        final Color JavaDoc color = UIManager.getColor(
1090                "Label.disabledForeground"); //NOI18N
1091
if (color != null) {
1092            border.setTitleColor(color);
1093        }
1094    }
1095
1096    private JLabel JavaDoc lblClassToTestValue;
1097    private ClassNameTextField tfClassName;
1098    private JTextArea JavaDoc txtAreaMessage;
1099    private JComboBox JavaDoc cboxLocation;
1100    private JCheckBox JavaDoc chkAbstractImpl;
1101    private JCheckBox JavaDoc chkComments;
1102    private JCheckBox JavaDoc chkContent;
1103    private JCheckBox JavaDoc chkExceptions;
1104    private JCheckBox JavaDoc chkGenerateSuites;
1105    private JCheckBox JavaDoc chkJavaDoc;
1106    private JCheckBox JavaDoc chkPackage;
1107    private JCheckBox JavaDoc chkPackagePrivateClasses;
1108    private JCheckBox JavaDoc chkProtected;
1109    private JCheckBox JavaDoc chkPublic;
1110    private JCheckBox JavaDoc chkSetUp;
1111    private JCheckBox JavaDoc chkTearDown;
1112
1113}
1114
Popular Tags