Download Screenshot of NetBeans IDE with a Java project open

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
NetBeans 6.5
User Guide
Version 1.0
2009-01-20
Copyright 2009
J. Kasprzyk, M. Brikman
Preface
The purpose of this document is to present a "user's guide" to some of the more important Java-related
features available in the NetBeans IDE (Integrated Development Environment). This document decidedly
Java oriented - all of the features that are discussed are presented in the context of the Java programming
language. It should be noted that there are literally hundreds of features available within NetBeans, many
devoted to languages other than Java - detailed information regarding the various options can be found in
the documentation and FAQs available at www.netbeans.org. Two specific site pages that may be of
interest are http://plugins.netbeans.org/PluginPortal/faces/MainPage.jsp (a list of optional features that
can be installed as needed) and http://www.netbeans.org/kb/trails/java-se.html (a set of Java-related
tutorials).
If you have experience with other Java-oriented IDEs or even with an IDE that is focused on other
languages (e.g., Visual Studio), NetBeans provides many of the same features - the following pages will
provide a quick overview of how to perform the common tasks encountered by developers on a regular
basis.
If you are new to the concept of an IDE, the number of topics presented in this document can be
intimidating. Please note the following:




There is no immediate need or reason for you to learn about the NetBeans topics presented in
this user's guide, so there is no need or reason for you to read this entire document in one
sitting. Let your instructor guide you to and through the topics and features as they become
relevant to the course. Use this document to supplement class demonstrations. It's all too easy to
miss a specific point during a demonstration and/or to forget how to accomplish a specific task:
this document is designed to address these problems.
Features will be demonstrated in class and/or in lab before you are expected to use them.
Hearing why a given feature is useful in a given context and then seeing how it is employed is an
important part of learning how to cope with any IDE.
Many of the following notes explain how to customize NetBeans to make it more efficient for
addressing specific software development issues. Figuring out what to customize and how to
customize it is a very real problem, and the customization process itself can be quite timeconsuming. To address this issue, some instructors create a "pre-customized" version of
NetBeans that is optimized for a specific class. This customized version comes complete with
specific settings and plugins (enhancements), and is ready to use as soon as it is installed. In
most cases, no additional customization of NetBeans will be necessary in the course of the
semester. If a customized version of NetBeans is appropriate for your course, it will usually
be made available on the Computer Science Department's file server on the R: drive - see
your instructor for the specific location.
NetBeans is a tool that is designed to make you more productive - rather than looking at it as "one
more thing to learn", look at it as something that will make the main objective of the course
(developing Java software) significantly easier to accomplish. Working with this tool and using it
as it was designed to be used will save you considerable time and can significantly diminish the
more frustrating aspects of learning a general purpose computer language such as Java.
Page 2 of 29
Table of Contents
Note : ... symbols in the table of contents and in the document are used to indicate particularly important information
Preface ............................................................................................................................................................................................ 2
Table of Contents ........................................................................................................................................................................... 3
Download and Installation Options ................................................................................................................................................ 4
 Before beginning Installation  ........................................................................................................................................... 4
Definition of netbeansHome  ............................................................................................................................................. 4
 Sources for NetBeans software  ........................................................................................................................................ 4
 Installation of a Customized NetBeans Version on a NON-LAB computer  .................................................................... 5
Un-installation of a Platform-Independent NetBeans installation .............................................................................................. 6
   Special Instructions for using NetBeans in Salem State College Computer Science Department labs    .......... 7
IDE configurations and settings ..................................................................................................................................................... 8
 Default JDK  ..................................................................................................................................................................... 8
 RAM requirements ........................................................................................................................................................... 8
 Java Documentation Access ............................................................................................................................................. 9
Code Navigation Toolbar ........................................................................................................................................................... 9
Memory Usage / Garbage Collection ......................................................................................................................................... 9
Main toolbar customization ........................................................................................................................................................ 9
JDK Installation.......................................................................................................................................................................... 9
JDK Management ..................................................................................................................................................................... 10
Library Management ................................................................................................................................................................ 10
Java Style and Presentation Rules Customization .................................................................................................................... 11
Project Creation and Execution .................................................................................................................................................... 12
 Creating a new project "from scratch" (no pre-existing Java code)  ............................................................................... 12
 Creating a new Project using pre-existing Java source code .......................................................................................... 12
Project Execution ..................................................................................................................................................................... 13
Project-level customizations and settings ..................................................................................................................................... 15
 Specifying JDK (Compiler) Options  .............................................................................................................................. 15
 Specifying JVM (Runtime) Arguments  ......................................................................................................................... 15
 Using predefined project configurations  ........................................................................................................................ 15
Code editing and formatting ......................................................................................................................................................... 16
Java Source File Creation ......................................................................................................................................................... 16
Code Creation and Editing ....................................................................................................................................................... 16
Source File Backups ................................................................................................................................................................. 17
Productivity Hints..................................................................................................................................................................... 17
Project Syntax Verification ...................................................................................................................................................... 18
 Comment Folding  .......................................................................................................................................................... 18
Keyboard shortcuts / code templates ........................................................................................................................................ 19
Javadoc - Coding and Generation of HTML-formatted documentation ....................................................................................... 20
JUnit - Test Case Creation and Execution .................................................................................................................................... 22
Plugins and Plugin Management .................................................................................................................................................. 24
PMD ......................................................................................................................................................................................... 24
CodeCoverage .......................................................................................................................................................................... 25
JavadocAnalyser ....................................................................................................................................................................... 26
Subversion - source code management utility .............................................................................................................................. 27
Screenshot of NetBeans IDE with a Java project open ................................................................................................................ 29
Page 3 of 29
Download and Installation Options
 Before beginning Installation 
Note that it is highly advisable to disable antivirus applications before you start installation. Some anti-virus products can
prevent IDE components from being configured correctly during the installation process; almost all (particularly activescan anti-virus products) will slow down the installation process significantly. If anti-virus software is disabled prior to
installation, remember to enable it when installation is complete.
Firewalls and application monitoring software will sometimes "sound an alarm" during installation - this is actually a
"good thing" (it shows that they are doing what they are designed to do - warn you when software installs and/or changes).
Give the software permission to allow the task at hand and installation should complete normally.
Some of the NetBeans installation files mentioned in the following sections will require the use of a "zip" utility. Most
operating systems have a built-in zip utility that can unpack zip files and create new zip files; for those situations where
your O.S. does not provide a zip utility or when you desire a zip utility with more powerful capabilities, there are a number
of packages available on the Internet. The Computer Science Department uses WinZip, a widely-used and stable product
(free trial download available at www.winzip.com; continued usage requires a one-time license purchase). Free options
include SecureZip (http://www.pkware.com/software-data-security/free).
This document assumes that NetBeans is being installed on a computer running a Windows Operating System. Editions of
NetBeans designed for Linux, Solaris and Mac O.S. are available at www.netbeans.org, as are specific installation
instructions. If you will be running NetBeans on something other than Windows, speak to your instructor for installation
and configuration options.
 Definition of netbeansHome 
There is a common term (notation) that is used throughout this document, mostly in the context of NetBeans installations:
o
netbeansHome: the folder (directory) where NetBeans software is installed. A typical example might be
C:\NetBeans6.5
In the context of Computer Science Department labs, the netbeansHome folder might be
R:\NetBeans6.5GeneralUse
This location is chosen during the installation of NetBeans, resulting in all of the files that collectively represent
the NetBeans IDE being located within this folder. Certain activities or options in this document require that one
or more of the files within the IDE be directly modified or referenced: the file that needs to be edited is presented
with netbeansHome prepended to indicate where the file is actually located, e.g., assuming the actual location of
netbeansHome is C:\NetBeans6.5,
netbeansHome\IDE\etc\netbeans.conf
would "expand" to
C:\NetBeans6.5\IDE\etc\netbeans.conf
The choice of where to physically place an installation of NetBeans is left to the person doing the installing. For
performance reasons, it is best to install NetBeans on an internal hard drive.
 While it is possible to install NetBeans on an external flash drive, performance (particularly launch time) will
significantly suffer if it is installed to any currently-available form of flash media.
 Performance of NetBeans installed on an external hard drive (portable or fixed) is usually almost
indistinguishable from that of NetBeans installed on a internal hard drive - but be aware that portable hard
drives must be treated with reasonable care if they are to work for any extended period of time.
 Sources for NetBeans software 

"Standard" Version. There are a number of versions of NetBeans 6.5 available at the NetBeans website
(www.netbeans.org). The various versions are configured for different operating systems and for different objectives
(available functionalities). One potential problem with these "standard" versions is that none of them have any of the
literally hundreds of "plugins" (add-ons, extensions) preinstalled, and selecting and then installing plugins tends to be
Page 4 of 29
time-consuming and confusing if you are an inexperienced programmer. The Computer Science Department has
configured versions of NetBeans that have been customized for specific learning environments and whose installation
and subsequent management has been simplified. Therefore, it is strongly recommended that you do not download
from the NetBeans website, but rather use one of the versions available from the Computer Science Department.

Customized Version. Your instructor may "customize" a version of NetBeans in order to optimize its functionality
for a specific course or project; otherwise, you will be referred to a standard Computer Science Department
configuration. The supplied archive (".zip" file) will NOT contain a standard self-extracting installer - "installation" is
accomplished by extracting the files into a specified location. It is very important to
o note the specific path to the file(s) as specified by your instructor, and
o extract all files!!!
 Installation of a Customized NetBeans Version on a NON-LAB computer 

Do NOT follow these instructions to install/access NetBeans on a Computer Science Department computer instead, use the instructions found in Special Instructions for using NetBeans in Salem State College Computer
Science Department labs.

There will be one file that is provided by your instructor to download, typically named
NetBeansversionName.zip,
e.g.,
NetBeans6.5GeneralUse-2009-01-01.zip or
NetBeans6.5CSC300-2009-01-01.zip
Be sure to use the path and file name specified by your instructor: use the specific folder specified by your
instructor to acquire the files! Files are usually available from the R: drive of the department's main server.

Note: The provided file does not include a JDK - it is assumed that a JDK has been previously downloaded and
installed on your system. A simple way to verify that a JDK has been installed is to launch Control Panel
(StartSettings--Control Panel) and see if "Java" appears as one of the entries; launching the Java entry will allow
you to determine the exact JDK version(s) installed. If no Java JDK is installed, one must be downloaded and installed
before the initial launch of NetBeans (use the latest release of the latest version available). Please see JDK Installation
for instructions.

To install NetBeans:
o Double-click NetBeans-versionName.zip: a zip utility will launch and provide you with the opportunity
to extract the contents of the file. Using the utility, specify the location where the software is to be stored (e.g.,
C:\), then allow the utility to extract the contents of the archive into the specified location. There will now be a
folder named NetBeans-versionName in the specified location. This folder (e.g. C:\NetBeansversionName) will henceforth be referred to as netbeansHome.
o To create a shortcut for launching NetBeans:
 Launch Windows Explorer and browse to the netbeansHome folder.
 Right-click "LauncherNetBeans6.5.bat", drag it onto a blank area of the desktop, and then choose "create
shortcut here".
 Right-click on the shortcut that you just created and click Properties, then
► Click the General tab and replace "Shortcut to LauncherNetBeans6.5.bat" with a shorter and more
obvious name (e.g., "Start NetBeans 6.5").
► Click the "Shortcut" tab and then click "Change Icon". A warning message that
"LauncherNetBeans6.5.bat contains no icons" appears; click OK. In the resulting "change icon" dialog,
browse to the netbeansHome folder and select "NetBeans6.5Icon.ico". Click OK, then click "Apply".
o Finish with OK.

IMPORTANT INFORMATION - LOCATION OF USER-SPECIFIC SETTINGS
o If you followed the preceding instructions correctly, NetBeans will NOT save any significant user-specific
information to your profile - it will instead be found in ...\versionName, e.g.,
netbeansHome\NetBeansPersonalSettings\versionName,
Page 5 of 29
e.g.,
C:\NetBeans-versionName\NetBeansPersonalSettings\versionName
Un-installation of a Platform-Independent NetBeans installation

Using Windows Explorer, browse to netbeansHome and delete the folder. Finish by deleting the desktop shortcut.
Page 6 of 29
   Special Instructions for using NetBeans in Salem State College Computer
Science Department labs   


NetBeans is not installed on Computer Science Department lab computers. Instead, it is installed on a read-only drive
on the main Department file server. In order to use NetBeans on a lab computer, you must first perform the following
tasks. Note that this is a one-time-only activity: once you complete the following tasks, you will be able to launch
NetBeans from any lab computer without needing to repeat these tasks, and indeed must not repeat these tasks (doing
so will "reset" your access to NetBeans back to its initial state, quite probably losing important information about your
work in the process).
There are multiple versions of NetBeans available on the department server. The location of the appropriate version
of NetBeans will be indicated by your instructor. The location will have a drive letter of R: followed by the path to
a specific folder, e.g.,
R:\instructorName\NetBeans6.5CSC301
or
R:\NetBeans6.5GeneralUse
This location will be referred to as netbeansHome in the following steps 1 through 3.
NetBeans setup tasks for Computer Science Department labs
(1) To create a shortcut for launching NetBeans:
o
o
Launch Windows Explorer and browse to the netbeansHome folder.
Right-click "Start R NetBeans6.5 GeneralUse", drag it onto a blank area of the desktop, and then choose "create
shortcut here".
(2) Verify that you accomplished the preceding actions correctly:
o
o
Using Windows Explorer, browse to the netbeansHome\NetBeansPersonalSettings folder. Make
note of the single folder name that appears in NetBeansPersonalSettings (you'll need it in the next step) - it
will be referred to as versionName.
Launch NetBeans (double-click the shortcut created in step 1). When NetBeans has launched, clicked the Help
menu item and choose About. The Userdir entry should be
H:\NetBeansPersonalSettings\versionName. If anything else appears in the Userdir entry, please
see your instructor for assistance.
Page 7 of 29
IDE configurations and settings
 Default JDK 



Changing the default JDK usually means that a more up-to-date JDK has been installed on your computer AND that
NetBeans was previously configured to launch with a specific JDK.
o Note that JDKs do NOT come with Java API documentation "bundled" - don't forget to download JDK javadocs
and extract them into the JDK's main folder when the new JDK is being installed.
o Note - when dealing with Computer Science Department lab computers, new JDKs will always have appropriate
Javadocs installed
First, the new JDK should be registered with NetBeans. Launch NetBeans and check if the desired JDK is already
registered with NetBeans as the default Java platform (ToolsJava Platforms); add the JDK via the "Add Platform"
button if it isn't listed. Note that you cannot change which JDK NetBeans considers the default JDK in this pane - the
actual change of default takes place because of the next step. Close NetBeans.
In the installation folder for NetBeans (referred to as netbeansHome), locate the following file:
netbeansHome\LauncherNetBeans6.5.bat,
e.g.,
C:\NetBeans6.5GeneralUsage\LauncherNetBeans6.5.bat.
Open the file by right-clicking and choosing "Edit". The line to be edited is
rem set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_11
REMOVE "rem" from the beginning of the line, then change the value AFTER THE ASSIGNMENT OPERATOR
(=) as appropriate to point to the JDK folder that you wish NetBeans to use by default, resulting in a statement that
might look like this:
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_12
 RAM requirements 

To change the default load / min / max RAM that NetBeans uses, in the installation folder for NetBeans (referred to as
netbeansHome), locate the following file:
netbeansHome\etc\netbeans.conf,
e.g.,
C:\Netbeans6.5\etc\netbeans.conf.
Open the file using a text editor (right-click, choose "Open With" WordPad, NOT WORD!). Change the
"netbeans_default_options" line, altering the parameter set for the line beginning with "netbeans_default_options" as
indicated below. Note that the numbers assigned to Xmx and MaxPermSize can be increased even higher if desired
AND IF there is sufficient RAM available, but the suggested values should be sufficient for even very large projects.
o Note that the "netbeans_default_options" statement may be very long. Use the scroll bar to locate the section of
test to be changed, and do not insert any line feeds for any reason - doing so will render the line meaningless to
NetBeans.
o The "netbeans_default_options" statement initially looks like this (formatted here for readability!!!):
netbeans_default_options=
"-J-client -J-Xverify:none
-J-Xss2m -J-Xms32m
-J-XX:PermSize=32m
-J-XX:MaxPermSize=200m
-J-Dapple.laf.useScreenMenuBar=true
-J-Dsun.java2d.noddraw=true"
while the edited version should look like this (formatted here for readability!!!):
netbeans_default_options=
"-J-client -J-Xverify:none -J-Xmx512m
-J-Xss2m
-J-Xms32m
-J-XX:PermSize=32m
-J-XX:MaxPermSize=512m
-J-Dapple.laf.useScreenMenuBar=true
-J-Dsun.java2d.noddraw=true"
This display has been edited to clarify the insertions and changes (highlighted in green) - as stated in the previous
bullet, do not insert line feeds during the editing process - just insert or change the line as indicated, then save the
file.
Page 8 of 29
Note that if you have installed a version of NetBeans customized and supplied by your instructor, this step should
already have been performed.
 Java Documentation Access 

Most IDEs will provide direct access to Java documentation if in the code editor you place the cursor directly on the
class or method of interest and hit F1 (function key F1), which is an almost-universal "hot key" to access Help.
NetBeans uses a different hot key - to access Java documentation, set the cursor and hit Alt+F1. NetBeans displays
documentation about the NetBeans IDE (not about Java) when F1 is hit.
o If you use Java documentation frequently and wish to configure NetBeans to use F1 to access Java
documentation, you can customize NetBeans by customizing the Keymap. Note - check the current functionality
of F1 before customizing the Keymap in case your installation has been preconfigured. You can check by hitting
F1 while the cursor is on a Java class or method name (e.g., String) - if Java documentation pops up, then this step
has already been performed.
 Use ToolOptions, click on Keymap, expand the GoTo entry (click the +), select Goto Javadoc, click Add
at the bottom of the Actions list, then hit F1, and then OK. If NetBeans displays a warning that F1 is already
assigned to the Help option, it can be ignored. F1 should now appear in the Shortcuts list (along with
Alt+F1). Click on Alt+F1, then Remove. Don't leave the Keymap window yet!
 Still in Keymap, expand the Help Entry, select the Help entry, click Add at the bottom of the Actions list,
then hit Alt+F1. Alt+F1 should now appear in the Shortcuts list (possibly along with F1 - if F1 does appear,
select it, then click Remove).
 Click OK to finish.
NetBeans should now respond to F1 by displaying Java documentation, and Alt+F1 by displaying NetBeans
documentation.
Code Navigation Toolbar


NetBeans has "forward" and "back" buttons similar to those in a browser - they are located at the left end of the code
navigation toolbar (located just below the code editor tab).
The same toolbar contains buttons for search functionalities (find selection, find next, find previous, last edit,
comment/uncomment).
Memory Usage / Garbage Collection

To indicate to NetBeans that garbage collection would be a good idea, click on the memory usage button in the toolbar
- this will force garbage collection in the very near future and can result in a significant drop in memory usage.
o If the memory usage entry is not present in the tool bar, right-click on an empty area of the tool bar and click
Memory.
Main toolbar customization

The toolbar can be customized by right-clicking in an empty area of the toolbar and choosing Customize. While most
of the available buttons are also available via the drop-down menus and/or context menus, judicious addition of a few
commonly-invoked functions can make repetitive actions simpler and faster.
JDK Installation



NetBeans 6.5 requires a minimum of JDK 1.5; the latest release of JDK 1.6 is strongly recommended.
Visit http://java.sun.com/javase/downloads/index.jsp, select a JDK (NOT JRE!!!) and then follow the download and
installation directions.
o While any JDK can be installed, it is strongly recommended that the latest release be installed and used by
NetBeans. Releases within an edition never add Java features, but each success release does contain optimizations
and/or security patches.
After installing the JDK, you must then download and install Java documentation: on the same page where you
downloaded the JDK, scroll to the bottom of the page and then follow the download and installation directions for
Java SE Documentation.
Page 9 of 29
o
o
It is important that you install the documentation into the folder where the JDK was installed - NetBeans will not
know where the documentation is if you put it anywhere else.
Java Documentation is usually supplied as a zip archive. To "install" the documentation, simply double-click the
zip file, then browse to the JDK folder and let the zip utility "expand" the contents of the archive into that folder
JDK Management

NetBeans can be used with any standard JDK. However, the location of a JDK must be specified to NetBeans
manually. It should also be noted that the installation of a new JDK or JDK update will usually not be visible to
NetBeans until this step is completed. Adding or altering existing JDKs is accomplished via ToolsJava Platform
Manager: this will launch the Java Platform Manager Wizard.
o
o
o
o
To add a new JDK, click Add Platform
In the Choose Platform Folder window, browse to the location of the new JDK. If you click on a folder and the
Next button remains disabled (grayed-out), the folder does not contain a recognizable JDK. Click Next once the
correct folder has been selected.
The Platform Name wizard usually recognizes the JDK and fills in the Platform Name automatically; if desired,
the name can be edited for ease of recognition in the future.
Note that documentation for a JDK is usually downloaded and stored in a separate step from loading and
installing a JDK. If documentation is not present, or is not saved to the same folder as the JDK, the Platform
Javadoc entry in this window will be empty. The JDK can still be used to compile a project, however, note that
there is a high likelihood that NetBeans' Code Completion will not work properly, and Java documentation may
not be available via F1.
 To determine if JDK documentation is present and visible, use ToolsJava Platform Manager; select the
Platform that you wish to check, then click the Javadoc tab. If the Platform Javadoc window is empty, the
platform doesn't know where the Java documentation is located: the best solution is to download the
documentation from www.sun.com and install (expand) it into the folder where the JDK is installed.
Restarting NetBeans after the documentation has been installed is usually enough to get the Java Platform
Manager to recognize the presence of documentation; if F1 still does not bring up Java documentation, use
the Java Platform Manager to select the JDK, click the Javadoc tab, and manually browse to the folder where
the documentation is located.
Library Management

Java classes that are referenced by a project but are not included in the JDK or physically included in the project
folder can and should be placed in libraries and then made accessible to specific projects on an "as needed" basis.
Note that a library needs to be registered with NetBeans only once, and can then be linked to by as many projects as
necessary.

NetBeans Library Creation
o To launch the Library Manager use ToolsLibraries
o Click New Library; in the window that appears, enter an easily-recognizable name (e.g., Oracle, MySQL,
Project13, etc.) and set the Library Type to Class Libraries, then click OK.
o Find and select the library that you just created in the list of libraries, then click on Add JAR/Folder; in the
Browse window that appears, browse to the location of the physical folder that contains the library of class files,
select all of the class/JAR/Zip files to be added to the library, then click Add JAR/Folder. The class/JAR/Zip
file(s) should now appear in the Library Classpath. Additional JAR/Zip files can be added to the library by
repeatedly using the Add JAR/Folder button.
o While a library can contain many entries (JAR/Zip files), it is more efficient to create multiple small libraries than
it is to create one (or a few) large libraries. The larger the library, the longer it will take the compiler to examine
the library during a build/compilation: libraries for many commercial products (image manipulation, speech
synthesis, database connectivity) often contain megabytes of information representing thousands of referenceable
classes and images.
 It is particularly important that resource classes provided by an instructor for a specific project be placed in
their own library - it is highly likely that combining resources from multiple projects will result in naming
conflicts that the Java compiler will be unable to resolve.
o When creating a library that is to provide access to Java classes supplied by your instructor, first save the
provided file(s) to a folder on your hard drive (e.g., C:\CSC201J\ProvidedLibraries\Project13), then create a new
library as described above. The appropriate files can be added by browsing to the folder that you copied the
provided files into; select all of the JAR/Zip archives that are in the folder.
Page 10 of 29

NetBeans Library Referencing
o To add an existing library to the list of libraries to be referenced by a project, first open the project
o Right-click on the project name in the project pane and choose Properties
o In the Project Properties window, select Libraries in the Categories pane, make sure that the Compile tab is
selected, then click Add Library (right side of window); in the window that pops up, select the library that is
required by the project, then click Add Library.
o Additional libraries can be referenced by repeating the previous step above.
o Note: if a project will be regularly migrated from a lab computer to a personal computer, it is very important that
all required libraries be located in the same physical folder location in both contexts. If a library on a personal
computer points to FolderA but that same library points to FolderB on a lab computer, the project properties may
have to be manually reset every time a migration takes place. Most libraries that are to be referenced are part of
the standard JDK and are pointed to automatically by NetBeans; the great majority of additional libraries are
either part of the NetBeans IDE (and are already "built into" the list of known libraries) or part of another
software package (e.g., Oracle, MySQL, etc.): as long the software package is installed on your personal
computer to the same folder as it is installed into in lab computers, library configuration will be simple and
transparent.
Java Style and Presentation Rules Customization



Java code has a number of style rules that govern concepts such as indentation, spacing and naming. NetBeans can
indent and check the spacing of your code automatically.
NetBeans can be distributed with style and presentation rules preconfigured. Check with your instructor to determine
if you have such a distribution - if this is the case, it is strongly suggested that you leave the various settings "as is"
until explicitly told to make changes by your instructor.
Customization of the rules is available via ToolsOptions: this will launch the Options window.
(NOTE: style rules have almost certainly been pre-configured based on department or instructor standards - do NOT
customize the rules using the following instructions unless instructed to do so!)
o In the top row of options click Editor:
 Click the General tab
► In the area labeled Code Folding, check the Use Code Folding option, then check the Collapse by
Default option for Javadoc Comments and Initial Comment (clear any other checks)
► In the area labeled Code Completion, check Auto Popup Completion Window, Case Sensitive Code
Completion, Insert Closing Brackets Automatically, Show Documentation Next to Completion, and
Show Deprecated Members
► In the Camel Case Behavior area, check Enable Camel Case Navigation
 Click the Formatting tab.
► Set the Languages entry to All Languages using the dropdown list
 check "Expand Tabs to Spaces" set Number of Spaces per Indent and Tab Size to 4, and Right
Margin to 90.
► Set the Languages entry to Java using the dropdown list
 set Category to Tabs and Indents, then check Indent Top Level Class Members and Indent Case
Statements in Switch
 set Category to Alignment, check all Options under New Line EXCEPT "after modifiers"
 set Category to Braces, set Braces Placement to "New Line" for all options, check "Special 'else if'
treatment, and set all Braces Generation to "Generate"
o Click OK to save the settings
Page 11 of 29
Project Creation and Execution
 Creating a new project "from scratch" (no pre-existing Java code) 



FileNew Project will open the Create Project Wizard, as will the New Project button ( , 2nd from the left in the
Toolbar)
In Step 1, expand the Java category, then select Java Application for the specific project type. Click Next.
In Step 2:
o Enter the name of your project in the Project Name text area. Note that project names are NOT case sensitive.
o Browse to the location where you want the project to be stored:
 If you have not previously done so, create a folder in a "safe" location that you can easily remember and
place ALL of your projects in that folder (you can use Windows Explorer for this task or you can use the
"Make New Folder" button provided in the Browse dialog).
 When working in Computer Science labs, it is very important that you do NOT accept the default location of
C:\Users\userAccountName. Doing so will save your project into your roaming profile, which will have a
significant long-term impact on your profile size and ultimately on your ability to log in and log off
successfully! In Computer Science labs, projects are normally stored on the H: (server) drive.
o Leave the "Set as Main Project" option checked.
o Check the "Create Main Class" option unless your instructor tells you otherwise.
 Checking this option will cause a source file containing the Java class named Main.java to be created
automatically - this class is often used as a standard starting point for a project. You may rename this file if
so advised by your instructor.
o Click Finish.
A new project with the specified name should be created. If the "Create Main Class" option was selected, the
Main.java class source file will be open in the editor pane, otherwise the editor pane should be empty.
While not required, it's a good idea to set the JDK (Compiler) and JVM (Runtime) options for the project at this time.
See "Setting JDK (Compiler) Options" and "Specifying JVM (Runtime) Arguments" for details.
 Creating a new Project using pre-existing Java source code 

There are two options for creating a new Project from existing files :
o use Explorer to set up the project infrastructure and copy the appropriate files into the project infrastructure, then
use NetBeans to create the project
OR
o

use NetBeans to create a new "empty" project infrastructure, close the project, use Explorer to copy the
appropriate files into the project infrastructure, and then re-open the project.
To create a new project starting with Explorer:
o Using Windows Explorer
 Create a folder for the new project, then within that folder create subfolders named src and test
 Copy (not move!) files from wherever they are available into the new project's src folder, taking care to
preserve package structure. Each Java source file to be copied must be placed in a folder with the same name
as the package that the Java class is declared to reside in, e.g., a Java source file named Student that includes
a statement package student would be copied into the folder
...\NewProjectName\src\student; similarly, a Java source file named Main that includes a statement
package main would be copied into the folder ...\NewProjectName\src\main. Note that Explorer
will create a folder for you by right-clicking in the folder where you want the new folder to reside and
choosing NewFolder, then editing the name of the new folder.
► Note - a simple way to copy files into the new project is copy to the folder that contains the files from
the original folder into the new project folder - Windows copies the folder structure along with the files.
If some of the copied files are not necessary, then can be deleted.
Page 12 of 29
o

In NetBeans, use FileNew Project or , then in the Java Category select Java Project with Existing Sources
and click Next.
 Browse to the project folder that was created in the previous step
 A project name may be supplied - change it to something meaningful
 Click Next
 In the Source Packages Folders area, click Add Folder, click on the src folder that appears, click Open
 In the Test Packages Folders area, click Add Folder, click on the test folder that appears, click Open
To create a new project starting with NetBeans:
o Using NetBeans
 Create a new project (see Creating a new project "from scratch")
► Uncheck the "Create Main Class" if instructed to do so or if you will be using a Main class from another
project.
 Close the project, but leave NetBeans running.
► It is important to close the project before proceeding to the next step - adding or other manipulating files
that are part of an open project can cause synchronization problems in the future.
o Using Windows Explorer
 Browse to the folder that contains the new project that was created in the previous step
 Copy (not move!) files from wherever they are available into the project's src folder, taking care to preserve
package structure. Each Java source file to be copied must be placed in a folder with the same name as the
package that the Java class is declared to reside in, e.g., a Java source file named Student that includes a
statement package student would be copied into the folder ...\NewProjectName\src\student; similarly, a Java
source file named Main that includes a statement package main would be copied into the folder
...\NewProjectName\src\main. Note that Explorer will create a folder for you by right-clicking in the folder
where you want the new folder to reside and choosing NewFolder, then editing the name of the new folder.
► Note - a simple way to copy files into the new project is copy to the folder that contains the files from
the original folder into the new project folder - Windows copies the folder structure along with the files.
If some of the copied files are not necessary, then can be deleted.
o Back in NetBeans, open the new project - the files that were just copied should now appear in the project pane in
the source packages subtree. A Clean and Build may be necessary to get NetBeans to properly recognize and
synchronize the new files.
Project Execution


RunRun Main Project or or F6 will save all changed project files, build (compile) the .java project files, and then
execute the code in the project, assuming that there are no syntax errors. If there are any syntax errors, this option
behaves the same way as the Build Project option in the section Code Editing, subsection Project Syntax Verification.
Output will appear in the output pane
o NetBeans may display the results of preparing the project for execution, followed by any output, followed by a
"Build Successful" message, e.g.,
Hello World!
BUILD SUCCESSFUL (total time: 0 seconds)
o
If any runtime errors occur during execution, they will appear in the output pane, highlighted in red. In addition,
the line of code that was attempting to execute when the runtime error was detected is included and hot-linked to
the line of code in the class file: clicking on the link will place focus on the offending line of code in the editor
pane. The following display contains a commonly-encountered runtime problem:
Exception in thread "main" java.lang.NullPointerException
at junk.Main.main(Main.java:30)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
o
Correcting a runtime error is done the same way as correcting a syntax error - click the link to jump to the
offending line of code in context, edit the code to correct the mistake, and re-execute the project. It bears
mentioning that determining the actual cause of a runtime error is very often highly frustrating and timePage 13 of 29
consuming - in contrast, determining the cause of a syntax error is usually straightforward once some experience
has been gained. Even seasoned programmers with years of experience can find that tracking down the cause of
runtime errors in large-scale projects can be problematic.
Note: if the execution of a project references or produces a data file and the full path for the data file is not explicitly
given in the code, the default (assumed) location of the file is the root of the project folder.
Page 14 of 29
Project-level customizations and settings
 Specifying JDK (Compiler) Options 

To insert additional compiler options, right-click on the project in the project pane, select Properties, click on
Compiling. Add additional options as desired in the Additional Compiler Options area. A particularly useful option,
particularly when dealing with inheritance, type casting, and generics, is -Xlint - this will cause warning as well as
fatal errors to be displayed in the output pane whenever code is compiled.
 Specifying JVM (Runtime) Arguments 

To change the default execution (runtime) configuration, right-click on the project in the project pane and select
Properties, then click on Run.
o to pass command-line arguments to the main() method, type the values (separated by a space) into the Arguments
area.
o to enable runtime execution of assert, add -ea to the VM Options area. 
o to add additional runtime parameters, type them into the VM Options area, separating the options with a space
 Using predefined project configurations 

Each project has its own set of properties. A specific subset of these properties governs project execution: when the
Set Project Configuration box is set to "default configuration", the properties of the project related to execution govern
execution. Additional configurations that can be used to "override" the default settings can be defined by clicking the
dropdown arrow on the Set Project Configuration box and choosing "customize" - in the resulting dialog, choose an
existing configuration from the Configuration dropdown list, or type in a new name to create a new configuration.
This feature allows a project's execution to be switched from one configuration to another ("standard execution" vs.
"active asserts" vs. "extensive diagnostics" vs. ...) very easily, just by selecting the appropriate configuration in the Set
Project Configuration box before executing the project.
Page 15 of 29
Code editing and formatting
Java Source File Creation


Select (click) your current project in the Projects pane
o Make sure that the project is the current "Main Project". NetBeans indicates the current "Main Project" by
boldfacing its name; to set a project to be the "Main Project", right-click on the project name in the project pane
and select "Set as Main Project"
o Multiple projects can appear in the Project pane - if you're not careful, your source file will be stored in the wrong
project, and moving the file into the correct project is problematic. The simple way to avoid problems is to make
sure that the project that you are working on is set as the Main Project.
FileNew File will open the New File Wizard, as will the New File button ( )
o In Step 1 choose Java from Category and Java Class from File Types. Click Next.
o In Step 2:
 Enter your source file name in the File Name text area. Note that source file names ARE CASE SENSITIVE,
and remember that source file names (and Java class names) should always begin with an uppercase letter,
e.g., Student, not student, or MyClass, not myclass.
 Don't change the Project text area
 Set the Location text area to Source Packages
 Choose a name for the package in which the source file is to be stored. NEVER LEAVE THIS FIELD
EMPTY!!! Note that package names ARE CASE SENSITIVE. By default, the package name should be the
same as the class file name except that it should be all lowercase, e.g., the package name for MyClass.java
should be myclass. In some cases the class should be added to a pre-existing package - select one from the
drop-down list that is provided; in yet other cases a new specific package name must be created, in which
case type over the supplied package name (NetBeans will create the appropriate folder structure)
 Check the Created File display area to verify that the source file will be stored in the proper location (which
will be the project folder). The right end of the path name to the file should read
projectPath\src\packagename\ClassName.java, e.g.,
H:\JavaProjects\MyFirstProject\src\myclass\MyClass.java
 A new source file with the specified name should be created and opened in the editor pane.
Code Creation and Editing





Creating and editing Java code is very similar to editing text using a word processor or test editor. Additional
capabilities and features are built into the code editor of NetBeans in order to make the creation and maintenance of
Java code more efficient. A few of the more significant features are on-demand documentation (place the cursor on a
class or method and hit F1 or Alt-F1), context-sensitive code suggestions, active error detection, and automatic
indentation and formatting. The details of the code editor are not covered in this document: a demonstration of the
features is usually presented when the IDE is introduced, and many of the features are self-explanatory when
encountered.
Pre-emptive warning: it is never a good idea to edit any source code, regardless of language, with an actual word
processor (e.g., Microsoft Word). Word processors use hidden markup codes, special characters and Unicode to affect
text presentation - the inclusion of any of these is guaranteed to generate syntax errors when the code is eventually
compiled. Use the editor provided with your IDE; if source code must be edited outside of the IDE, use Wordpad.
To open a Java source file (henceforth referred to simply as a source file) for editing, the first step is always to use
NetBeans to open the project that the source file is part of (FileOpen project, or ), and only then open the source
file by drilling down to the file in the Source Packages tree of the project pane.
o A source file is one component of the many that make up a project: editing a source file directly (that is, without
first opening the project and proceeding as follows) will cause the source file to change, but the project will be
unaware of the changes - the consequences can be quite confusing. To put it another way - never open a project
component such as a source file directly (e.g., via Windows Explorer or WordPad) - always open it within the
context of NetBeans, and always via the project that the source file is part of.
Once the project is open, expand the project in the project pane, then expand Source Packages, and finally expand
Source Package's subfolders until the file that is to be edited is located.
Double-clicking a file will open it in the editor pane. As many files as desired can be opened by double-clicking on
each in turn; alternatively, expand all of the subfolders of Source Packages, then hold down Ctrl while selecting the
files to be opened: when all files have been selected, right-click and select Open.
Page 16 of 29




NetBeans can end up with many open panes with its main window: this can often cause the editor pane to be restricted
in size, particularly horizontally.
o Any pane can be resized horizontally by placing the cursor on a vertical margin: once the double-headed arrow
appears, click and drag as desired.
o Any pane can be expanded to fill the screen horizontally by double-clicking the pane's tab; to return the IDE/pane
to the previous display configuration, double-click again.
Line numbers can be made to appear in the editor pane by right-clicking in the left gutter (vertical gray area on the left
vertical margin) of the editor pane and selecting "Show Line Numbers".
Extensive Java language documentation is available directly within NetBeans. Simply place the cursor on the class or
method of interest and hit the Java documentation "hot key"- the appropriate Java documentation will appear in a
browser window. The Java documentation hot key is either Alt-F1 or F1 - please see the Java Documentation Access
entry in the IDE Configuration and Settings section for details and configuration options.
As with any computer application, it is a good idea to save your work regularly. NetBeans creates and maintains a
number of files in the background, so to save time and to be sure that all relevant files are saved, use Save All (
).
Source File Backups
Many IDEs automatically make "archive" copies of files as changes are made, thus providing a form of backup. NetBeans
generates backups in a compressed format - to access and examine backups, you have two options:
 use VersioningLocal HistoryShow Local History, then browse to the version of the file that you are interested in.
A "differencing" window will appear that shows the differences between the selected and current file, and allows
customized editing of the current file (move code from the older version into the new version, delete code from new
version).
 use VersioningLocal HistoryRevert, then select an older version of the file to revert the current version to. It is
important to make sure that you are reverting to the appropriate version before you click "revert" - the easiest way is
to use Show Local History (described above) to examine the older versions, and only then use Revert.
Productivity Hints



FINDING CLASS ELEMENTS: The Navigator pane of the IDE (usually appearing under the Projects pane) contains an
"inventory" of all of the attributes and methods that exist within the source file that is being displayed in the editor
pane (if this pane is not visible, use WindowNavigatingNavigator). This inventory pane gives you a quick,
effective way of determining what you have already defined and how you defined it (in particular, it's a quick way to
check how you spelled your method and attribute names). It also gives you a quick way to navigate within your code double-click on an attribute or method and NetBeans will center that line of code in the editor pane, highlight it, and
put the cursor on that line.
CLASS EXPLORATION AND CODE COMPLETION: A useful learning/exploration feature of NetBeans is "Code
Completion". This feature will automatically pop up a list of possible choices for the remainder of a command that
you are typing if you happen to be typing a class or object name. For example, if you have just typed the Java class
name "System" followed by the "dot operator" (i.e., System.), a list of the methods and attributes within that class that
are relevant to the current context pops up: you can scroll through the list, select your choice, and hit "enter",
whereupon NetBeans inserts the selected entry into your code. While this feature can reduce the number of typing
errors, its major value is as a tool to explore Java's vast collection of built-in classes: rather than spending time and
effort memorizing how a classes' methods are named and what their parameters are, this feature will present them to
you whenever you make use of the class.
BRACES: Java is heavily dependent on the proper use of brace pairs ({}) to recognize instructions and whether the
instructions are legal and correct in the context in which they are being used. Incorrect use of braces can "confuse" the
compiler, causing it to generate errors that are hard to understand and are even outright incorrect. While using braces
properly requires a non-trivial understanding of basic Java syntax, NetBeans will make life significantly easier with
respect to avoiding and/or detecting errors caused by incorrect use of braces if you do the following:
1) If you haven't already done so, set the formatting style rules to place braces on separate lines. Detecting
possible brace-related problems is MUCH, MUCH easier if your code is properly indented!
2) REGULARLY make use of NetBeans' formatting capability to check brace alignment (right-click in the
editor pane, choose Format) - at a minimum, format after you complete each method. If after formatting your
alignment "looks wrong", the odds are VERY high that you have either a missing brace or an extra brace.
3) If you want to see how NetBeans is "pairing" braces, place the cursor just before or after a brace. The
corresponding brace will then be highlighted. If you have highlighted a left (opening) brace ({), scrolling
DOWN will eventually reveal a highlighted right (closing) brace (}) if there is one that Java thinks "pairs"
Page 17 of 29
with the left one. When inside a method, if the closing brace doesn't appear within the current method, then
you're definitely missing a closing brace. The same logic applies if you highlight a right brace, except that
you would scroll UPWARDS.
4) When you create a new method, type the method header, hit "enter", type an opening brace, then immediately
hit enter - NetBeans will then supply the closing brace, with a blank line in between the braces and the cursor
on that blank line. By letting the IDE supply the closing brace, the odds on you leaving one out decrease
dramatically. This technique works in ALL circumstances when braces are called for (e.g., if and while
structures), not just when creating a method.
Project Syntax Verification


The validity of the syntax of the Java statements in your project can be checked by performing a "build" of the project.
RunBuild Project ( )will save all changed project files and then perform syntax checks on all project components
(classes), as will the Build Project button on the Toolbar.
o An alternative is to use the Clean and Build option (RunClean and Build Project, or the Clean and Build button
( ) - this option is necessary when any class files are moved from one package to another (because of incorrectly
typed names and/or design changes to the project). For complex projects, Clean and Build will take slightly
longer, but is more likely to eliminate any "false positives" in terms of apparent errors that display because class
files have not been properly synchronized.
The outcome of the build will be displayed in the Output pane, which should appear at the bottom of the NetBeans
window
o Information regarding syntax errors will appear in both the editor pane and in the output pane, but in different
formats. The following display shows two syntax errors as they would appear in the output pane. In the following
sample displays, the italicized lines are automatically provided by NetBeans whenever the project is processed
(note that the italics are provided for highlighting only - the lines are not italicized in NetBeans).
init:
deps-jar:
Compiling 1 source file to H:\JavaProjects\HelloWorld\build\classes
H:\JavaProjects\HelloWorld \src\junk\Main.java:29: cannot find symbol
symbol : method printline(java.lang.String)
location: class java.io.PrintStream
System.out.printline("Hello World!");
H:\JavaProjects\HelloWorld k\src\junk\Main.java:30: cannot find symbol
symbol : variable halt
location: class junk.Main
System.exit(halt);
2 errors
BUILD FAILED (total time: 0 seconds)
o
o
o
 Clicking on an error link (in blue in the display) in the output pane will cause the offending line of code to
appear in the editor pane - this provides a quick way of looking at a mistake "in context", which is usually
important in determining the cause of the error message. 
Note that correcting a mistake will NOT remove the mistake from the output pane, and will sometimes NOT
change any error indicators in the editor pane. If the error indicators in the editor pane do not change as a result of
the edited changes, the project must be built again to determine if the edited changes have corrected the problem.
It bears mentioning that with experience, determining the actual cause of a syntax error is usually straightforward.
 Comment Folding 


 ToolsOptionsEditor General
o Check "use code folding", then check Javadoc Comments and Initial Comment - this will fold/hide javadoc
comments, which can be visually distracting and eat up a lot of vertical display real estate. Comments can be
expanded by clicking the "+" sign; alternatively, they can be viewed without expansion by hovering the cursor
over the folded comment. Folded javadoc comments appear as
non-javadoc comments can be folded by enclosing them between the following XML statements
//<editor-fold defaultstate="collapsed" desc="description">
//</editor-fold>
Page 18 of 29
o
o
o
o
"description" can be replaced with any string - it's what will appear when the structure is collapsed (folded).
comments folded this way appear as
or
// is required so that the XML is not compiled as Java code; they also make the notation irrelevant when viewed
outside of NetBeans, e.g., in Eclipse.
actually, anything can be placed between the opening and closing editor-folds, including code - whatever appears
between the editor-folds will be folded ("disappeared" and replaced with the supplied desc string). As with the
standard code folding described earlier, folds can be expanded and refolded via the "+", and can be viewed by
hovering the cursor over the description string.
Keyboard shortcuts / code templates

ToolsOptions, then EditorCode Templates. To add a new shortcut, click New, choose an abbreviation and click
OK, then, in the Expanded Text tab, type in the code that you want inserted. Click the Description tab and enter a
description, if desired. Click OK to finish. To make use of a shortcut, type the abbreviation in the code pane and then
hit enter - the Expanded Text that was specified will be inserted in the code in place of the abbreviation. Example:
o To insert the XML code for a custom code fold, create a new template as follows: choose an abbreviation (say
cft), specify the following in the Expanded Text pane:
//<editor-fold defaultstate="collapsed" desc="${DESCRIPTION}">
${selection line}${cursor}//</editor-fold>
To make use of the shortcut, simply select the text to be hidden, click the hint indicator that appears in the left
margin, and select "Surround with //<editor-fold...". Alternatively, put the cursor at the left margin, type the
abbreviation (cf) and immediately hit Tab. Proceed to type a comment between the XML delimiter statements that
are supplied; don't forget to supply a meaningful description that will appear when the comment is folded.
o Templates and corresponding abbreviations can be created to allow rapid insertion of any set of statement(s) that
might be used frequently.
Page 19 of 29
Javadoc - Coding and Generation of HTML-formatted documentation

Javadoc-style comments can be created within Java source code by placing the cursor on a blank line immediately
above the code element to be javadoc-commented, typing /** (the standard Java signal for a javadoc-style comment),
then hitting Enter: NetBeans will then examine the following statement and generate javadoc entries appropriate for
the statement. For example, proceeding as described above for the Java statement
public static Coin createCoin(final double value)
results in the following being inserted just before the statement:
/**
*
* @param value
* @return
*/





The lines can then be completed with descriptions for the elements of the statement.
Generation of javadoc-implemented documentation can be accomplished via right-clicking of the project on the
project window and selecting Generate Javadoc. In order to ensure that accurate ("up to the minute") documentation
is generated, all editing changes must have been saved before generating the documentation: the simplest way to do
this is to "clean and build" before generating the documentation (either via the "clean and build" button or via rightclicking the project and selecting Clean and Build).
An overview of a project can be included in the generated documentation by placing the overview, formatted either as
a set of javadoc comments or as an HTML body, in the src folder. To get javadoc to include the file in the
documentation, it must be specified via the -overview option (use Project PropertiesBuildDocumenting pane to
set this and other documentation properties). The file is supposed to be included in the documentation automatically if
it is named overview.html.
NetBeans allows a number of javadoc options to be specified via Project Properties: right-click on the project in the
project pane, select Properties, and then click on Documenting. Type the option(s) and argument value(s) into the
Additional Javadoc Options pane. Checking Preview Generated Javadoc will cause the default web browser to launch
and view the generated javadocs whenever they are (re) generated.
To view the generated documentation outside of NetBeans, go to projectFolder\dist\javadoc and launch index.html.
o Alternatively, in NetBeans, put the cursor on any component that appears in the generated documentation and hit
the Help function key (function key 1 (F1) in NetBeans 6.5). Once the viewer launches, the project overview (and
other documentation levels) can be reached via the top navigation bar.
If the number of options to be specified is large and/or files need to be specified without explicit paths, an alternative
to using Project Properties is to edit the build.xml file that is generated by NetBeans for every project: this file can be
found in the project folder (same level as the src folder). Edit the file using Wordpad or by right-clicking on it in
NetBeans and choosing Open (the latter is better if you'll be making multiple changes - right-clicking in the editor will
reveal a format option, which is very helpful in dealing with xml tags). The build.xml file supplied by NetBeans is
little more than an import of a default build file. (The default build implementation can be found in nbproject/buildimpl.xml, but note that this file should NOT be edited - use it as a source of ideas.) Add the following xml code to the
build.xml file, immediately before the final line of the file (which should be </project> and which must remain
</project> after your insertion):
<!--===============
JAVADOC SECTION
===============-->
<target depends="init" name="-javadoc-build">
<mkdir dir="${dist.javadoc.dir}"/>
<mkdir dir="dist/javadoc/notes"/>
<copy todir="dist/javadoc/notes">
<fileset dir="notes" excludes="" includes="*.html,*.htm,*.pdf"/>
</copy>
<javadoc
additionalparam="${javadoc.additionalparam}"
author="${javadoc.author}"
charset="UTF-8"
destdir="${dist.javadoc.dir}"
docencoding="UTF-8"
encoding="${javadoc.encoding.used}"
failonerror="true"
noindex="${javadoc.noindex}"
nonavbar="${javadoc.nonavbar}"
notree="${javadoc.notree}"
private="${javadoc.private}"
source="${javac.source}"
Page 20 of 29
splitindex="${javadoc.splitindex}"
useexternalfile="true"
windowtitle="${javadoc.windowtitle}"
use="${javadoc.use}"
version="${javadoc.version}"
overview="ProjectOverview.html"
doctitle="Overview of ThreadedSearch Example Project"
header="ThreadedSearch Example Project"
linksource="true"
stylesheetfile="notes/TweakedCSSJavadocStyleSheet.css"
>
<classpath>
<path path="${javac.classpath}"/>
</classpath>
<fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}">
<filename name="**/*.java"/>
</fileset>
</javadoc>
</target>
<target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview">
<nbbrowse file="${dist.javadoc.dir}/index.html"/>
</target>
<target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/>
o
o
o
o
All of the code except the lines in boldface is copied from nbproject/build-impl.xml.
Indentation doesn't matter (but makes the code a lot easier to read and debug!).
The lines in boldface represent personal "customizations". A sample customized build.xml file may be available
from your instructor upon request.
Javadoc statements can contain links: if the files to be linked to are to be physically incorporated into the
generated documentation in a simple, automatic manner, then the initial set of customizations in the preceding
bullet must be made, and all files that are linked to within the javadoc statements must be placed in a folder
named notes that exists in the project directory (same level as the src folder). Placing the files to be linked to in
the /notes folder will ensure that when javadoc is generated, all files referenced by the documentation are
included in the generated folder.
Page 21 of 29
JUnit - Test Case Creation and Execution





JUnit is a standardized framework for writing repeatable tests. In combination with an IDE designed to work with
JUnit, it allows for the automated creation of a test "skeleton" (a class containing a set of method headers customimplemented to make generating a comprehensive set of tests for your Java code easier and more convenient). Once
the test skeleton has been created, it is hand-customized to contain the specific actions needed to demonstrate that the
code being tested meets its requirements. Running the test(s) from within the IDE is simple and convenient - the JUnit
framework takes care of all of the details related to running the tests and collecting the results. JUnit has been in wide
use for almost as long as Java has been available, and numerous extensions have been created to further enhance its
capabilities.
NetBeans 6.5 comes with JUnit 3.x and JUnit 4.x bundled - no additional steps are necessary in order to be able to
make use of JUnit.
o  JUnit 4.x adds a number of convenience features to those supplied by JUnit 3.x - use JUnit 4.x unless there is
an explicit reason for maintaining compatibility with JUnit 3.x. 
Creation of a test skeleton
o To have NetBeans create a test skeleton for you, in the editor pane open the source file for which you want to
create a test skeleton, then choose ToolsCreate JUnit Tests, or use the Create Test Skeleton button ( )
 Note: if Create JUnit Tests does not appear in the Tools list, a test package folder must be created and
registered with your project. In the project pane, right-click on the project and select Properties. Click on
Sources, then, in the Test Packages Folders area, click on Add Folder. In the resulting Add Test Folder
dialog, browse to your project folder: select the folder name and it will appear (along with its complete path)
in the File Name area. At the END of the file name area (that is, appended to the end of the path/folder
name), type in \testFolderName, e.g., \test. Click Open: this will close the Add Test Folder dialog.
The folder that you added should now appear in the Test Package Folders area, under both Package Folder
and Label. Click OK to close the Project Properties wizard. Create JUnit Tests should now appear in the
Tools list (remember to give focus to the source file before clicking on Tools).
o Once the JUnit test(s) have been created, the project subfolder Test Packages in the project pane will be
populated. The structure of the Test Packages subfolder matches that of Source Packages (i.e., Test Packages
contains packages, each of which contains JUnit test class(es)).
o A specific JUnit test can be opened by double-clicking it or by right-clicking and choosing Open.
Note that if a JUnit test skeleton is "re-generated" (that is, ToolsCreate JUnit Tests is invoked a second time for a
given class), NetBeans will recognize that the JUnit test code already exists - it will examine the existing JUnit test
code and will not change any existing code. If additional methods were added to the source code for a given class after
a test skeleton was initially generated and customized, subsequent usage of ToolsCreate JUnit Tests will cause
NetBeans to add additional code (in default skeleton form) only for the additional methods, while leaving pre-existing
code unchanged. This is a very nice feature, as additional methods are added to classes regularly during development,
enhancement and maintenance: being able to have NetBeans "incrementally" generate unit test stubs is a great timesaver.
Customizing the test skeleton
o Begin by opening a JUnit test class
o A set of test-related "house keeping" methods is included: they range from setUpClass() to teardown(). Each is
preceded with an annotation, which must not be altered or removed. Housekeeping methods that are deemed
unnecessary can be deleted (along with their annotation). Since they are all provided with empty
implementations, leaving unnecessary methods in the test class will do no harm, and may be useful in the future if
testing requires them due to changing test requirements.
o Documentation for each of the included housekeeping methods and annotations can be found in a number of
locations. Formal JUnit documentation can be found online at http://junit.sourceforge.net/javadoc_40/index.html.
You can access the same documentation within NetBeans by placing your cursor on one of the housekeeping
method headers and invoking Help (F1) assuming that JUnit documentation has been copied into the correct
folder (i.e., NetBeansInstallationFolder\testtools\docs ). For each public method in the class for which the JUnit
test case was created, a corresponding method will exist with original name pre-pended with test and a return type
of void (e.g., public String getSSN() would cause public void testGetSSN() to be created).
Each of these methods is preceded with the annotation @Test, which signals to the Java compiler and to JUnit the
role of the method. It is important that the annotation and method name not be altered - otherwise, the JUnit
processor may not recognize the method as being related to testing, and could consequently ignore it during test
execution.
Page 22 of 29
o
The test method will contain JUnit's "best guess" as to what variables need to be defined and what methods need
to be invoked in order to perform a simple test of the corresponding method in the Java class. It is worth noting
that:
 NetBeans is making an educated guess as to what code to generate - which means that the generated code
will often be incomplete, and will occasionally be inappropriate.
 The generated code will contain, at a minimum:
► System.out.println("methodName"); (this will display in the JUnit output panel)
► The last two lines will be
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");

The comment is an explicit reminder to check the preceding lines of generated code and to remove the
"fail" statement. The "fail" statement is included in order to force you to check the generated code and, at
a minimum, remove the "fail" statement - a "fail" statement causes JUnit to report that something
inappropriate was detected during the test of the method, and that the test will be reported as a failure.

 The generated code is meant to be edited and "customized" to meet the specific demands of testing the
original method. 
 The generated code will almost always be incomplete.
 In order to test any non-trivial method, it is usually necessary to invoke the method multiple times, varying
the parameter values supplied and/or run-time context, in order to determine that the method behaves as
required under all specified circumstances. NetBeans will generate code for one invocation; it is up to you to
determine how many additional invocations are appropriate, and what data values and setup are necessary in
order to thoroughly test the method.
 Further details regarding test case generation are beyond the scope of this document. www.junit.org contains
many useful links and tutorials; http://junit.sourceforge.net/ is another excellent source of information. Your
instructor may make available an example project for which a complete set of tests has been implemented
Executing JUnit tests
o To test the entire project, use RunTest Project, or use the toolbar button ( ). To run a test for a specific class,
give the source file to be tested focus in the editor, then use RunTest File or use the toolbar button ( ). The
results of the test(s) will appear in a "JUnit Test Results" pane (same area of the IDE as the Output pane). Failed
tests are clearly indicated in the pane - to access the code for the specific test case that failed, double-click on the
failed test in the JUnit Test Results pane and the code will appear in the editor pane.
Page 23 of 29
Plugins and Plugin Management






Plugins are managed via ToolsPlugins
Settings contains a list of Update Centers that NetBeans will periodically check for updates and new plugins.
o The main centers that are of interest are:
 3rd party plugins: http://updates.netbeans.org/netbeans/updates/6.5/uc/final/thirdparty/catalog.xml.gz
 Plugin Portal: http://plugins.netbeans.org/nbpluginportal/updates/6.5/catalog.xml.gz
 Plugin Portal Update Center: http://plugins.netbeans.org/nbpluginportal/files/nbms/pluginportal-updatecenter.xml
 SQE Update Center: https://sqe.dev.java.net/updatecenters/sqe/updates.xml
 NetBeans: http://updates.netbeans.org/netbeans/updates/6.5/uc/final/stable/catalog.xml.gz
 NetBeans Beta: http://updates.netbeans.org/netbeans/updates/6.5/uc/final/beta/catalog.xml.gz
o Make sure that you check "force install into shared directories". Do this the first time that you use the
Plugins feature.
o Set the "Check Interval" for looking for updates to whatever your instructor recommends. Updating regularly
gives you access to the latest patches and plugin tools, but, it can also lead to an IDE that is looks and behaves
differently from what was originally distributed: take your instructor's advice.
Available Plugins is a list of what is available from the default Update Centers
o Note that entries within any of the tabs within Plugins can be sorted by clicking on a column heading.
o Plugin selection and installation is usually very straightforward:
 Select the plugin(s) to be installed. Note that it is generally safer to install one plugin at a time, in case any
problems develop.
 Click Install. The wizard will list the plugins to be installed; click Next.
 Accept the terms of any license agreements that appear; click Install.
 If a "Validation Warning" window appears, check the warning: if it is "Validation failed. The following
plugins are not signed", ignore the warning and click Continue.
 Click Finish. If NetBeans indicates that it needs to restart to complete the installation, allow it to do so.
Downloaded is a list of plugins that have been downloaded but not yet installed (most plugins install automatically
when the IDE is restarted; some require that the Downloaded page be selected and the plugin(s) be installed by
checking the Install column next to the plugin name and then clicking on Install). This page tends to be used when
accessing plugins from a non-NetBeans portal or center (see the Settings entry below for more details).
Installed will show the plugins that have been installed and their current status (Active (green checkmark) or Inactive
(red "x")).
NetBeans can generate a considerable amount of output pane "noise" related to its internal workings. If this
information is not of interest or use, install the Ant Output Filter plugin - this will eliminate this "noise" output. If the
output becomes important, it can be deactivated via the Module Manager (ToolsModule Manager, then expand the
Base IDE entry).
A few plugins in particular are very useful in promoting good code style and in pointing out possible problem areas.
Note: many of the plugins mentioned here are pre-installed in the versions of NetBeans available via the Computer Science
Department. To determine if a given plugin is already installed, use ToolsPlugins, click Installed Plugins, click the Name
column header to sort the list alphabetically, then examine the list. Attempting to install a plugin that is already installed is a
waste of time, and in certain circumstances can actually cause problems - check before you install!!!
PMD

PMD is a static code analysis tool that includes (literally) hundreds of "style rules" that represent "best practices" in
Java. Each rule can be turned on or off at will - which ones to turn on and off depend on the audience and the desired
affects. Rule violations are marked in the code pane but do not affect compilation (that is, PMD notations are invisible
to the Java compiler). Hovering over a line that is PMD-flagged will usually cause a diagnostic popup to appear - the
popup indicates the perceived problem and often offers explicit advice as to how to go about improving the code.
Again, PMD rule violations are not treated as errors but rather as warnings - and, given that PMD rules are essentially
"style" rules, they can be ignored if desired. Following PMD "advice" tends to result in code that is faster, smaller,
easier to understand, and easier to maintain.
o PMD is available from the SQE Update Center
Page 24 of 29

o
o
o
o
o
SQE Update center: go to https://sqe.dev.java.net/, then scroll down to find the update center. NOTE THAT
THERE IS A MODULE THAT MUST BE DOWNLOADED, THEN INSTALLED IN NETBEANS without this installation, the SQE update center will NOT be properly inspected for available plugins and/or
updates! Adding the URL to the Settings feature inside NetBeans' plugin manager is NOT SUFFICIENT again, download and install the plugin that will properly integrate SQE's update center into NetBeans' plugin
manager.
 After downloading the plugin, use ToolsPlugin, click the Downloaded tab, click Add Plugins, browse to
the downloaded file, click Open, then click Install.
To execute PMD, use QualityCode DefectsRun PMD, or use the PMD button in the main button bar: this
will produce a report in the output pane that details PMD violations.
To cause NetBeans to visually indicate lines of code in the code editor pane that violate PMD rules, toggle the
PMD button in the code editor button bar.
To observe and activate/deactivate the rules that PMD will evaluate (the "active" rules), use
ToolsOptionsQuality, then click the PMD entry. Individual rules are activated / deactivated by setting the
enabled checkbox. Note that any changes that are made will affect the NetBeans installation and therefore all
projects that are created in the future, not just the current project! Note that if you are running a version of
NetBeans that was "customized" for your class, you should check with your instructor before deactivating
(disabling) any rules; activating additional rules should be acceptable.
 There are a large number of rules: clicking on the "Rule" column heading will sort the list, making it
significantly easier to search.
Note that changes to the list of active rules are not immediately applied to an open project - PMD must be reexecuted in order to see the affects of the changes.
Note also that changes to code will cause PMD highlighting in the code to change as appropriate, but the PMD
report in the output pane will not change automatically - to update the report, re-execute PMD
CodeCoverage
o
Code Coverage is a plugin that works in concert with JUnit. JUnit is designed to assist with the implementation
and execution of test cases; Code Coverage will monitor the execution of the JUnit test cases and indicate the
lines of code in the class being tested that have actually been executed during the tests. Code Coverage will
highlight lines of code that have been executed during a JUnit execution in green; lines that have been partially
tested are highlighted in yellow; lines that are not executed even once during execution of the test cases are not
highlighted. After a JUnit test suite has been executed, the source code of the class being tested can be visually
scanned and any lines in further need of test execution are easily identified. Note that installing and activating
Code Coverage will have no affect whatsoever on source code display unless a JUnit test suite has been
implemented and executed!
► Code Coverage is available from the NetBeans Plugin center - select it and then click Install
► After installation, Code Coverage appears as an option (Coverage) in the project pane's context menu (rightclick on the project in the project pane). Code Coverage actions are governed by selections within this option.
 To activate this plugin (it is inactive by default), choose Activate Coverage Collection
 To deactivate, choose Deactivate Coverage Collection
 Note that Coverage Collection state is lost and defaults to deactivated whenever a project is closed and
whenever NetBeans itself is closed - it must be manually reactivated when the IDE and/or project is reopened.
► After activating Coverage, run the JUnit test suite that has been defined

A side affect of Coverage being active is that the JUnit Test Results may contain the lines
EMMA: runtime coverage data merged into [pathToProjectFolder\ThreadedSearch\coverage.ec] {in 0 ms}
EMMA: collecting runtime coverage data ...




for each component of the test suite. Viewing the source code for the classes that have been tested will
reveal source code lines are color-highlighted as described above.
Note that comment lines, method headers, and identifier definitions that do not contain executable code
are never color-highlighted
Statements that span multiple lines will only have the initial line color-highlighted.
If source code is being viewed in the code editor and JUnit is run, color-highlighting may not be
immediately updated; a second execution of JUnit will resolve the problem.
Altering source code will cause any highlighting in the edited area to be turned off, indicating that JUnit
needs to be re-executed in order to determine if the code changes resulted in changes in the degree of
code coverage.
Page 25 of 29
►
►
Code Coverage can produce a simple report indicating the percentage of code coverage: use the Show Project
Coverage Statistics option within the main Coverage option.
Remember that coverage highlighting can be turned off as described above.
JavadocAnalyser
o
Javadoc Analyzer will scan an individual file, a collection of files, or an entire project, looking for missing,
incomplete or incorrect Javadoc statements. A report is produced that lists all detected problems: clicking on a
problem will cause the code to appear in the editor window, and appropriate Javadoc statements can then be
inserted. Alternatively, problem(s) can be corrected by checking the box next to the problem(s) and then clicking
"fix now" - the plugin will insert appropriate Javadoc statements in "stub" format - you'll have to go to the actual
code to fill in details.
► To execute the Javadoc Analyzer, select a file, files, or project in the Projects pane, then use
SourceAnalyze Javadoc. If the resulting Analyzer Window is accidentally closed, it can be opened via
WindowAnalyzer.
Page 26 of 29
Subversion - source code management utility







For those new to the topic, source code control software is a tool that provides an automated means to avoid losing
your source files, to preserve intermediate versions of your code that can be used to see why new code is causing
problems, and even to revert to a previous version of the source. There are numerous tools available - Subversion is a
popular one that happens to be integrated into NetBeans. CVS is an older, simpler version that is also integrated into
NetBeans.
Note that while there is a Subversion plugin for NetBeans, which means that accessing Subversion is integrated into
the NetBeans IDE, Subversion is not included within NetBeans - this means that Subversion must be downloaded,
installed, and initially configured before it can be used within NetBeans. These steps can take place before or after
NetBeans is installed.
Subversion client AND server need to be installed and available (www.collabnet.com). Installing the server causes
two programs to be installed, svnadmin and svnlook, both related to creating a repository and administering it.
Installing the client causes one program to be installed, svn, which allows for interaction with an existing repository.
A Repository is created via svnadmin
o The path to the repository will be needed in NetBeans - write it down.
o Note that svnadmin and svnlook are command line tools - currently, there is no GUI interface available to make
the process of creating and administering a Repository convenient (there are GUI interfaces for the Subversion
client (details below)).
o Creating a Repository is simple - create a folder where you want the repository to reside, open a command prompt
and cd to that folder, then enter a svnadmin create repositoryName command, e.g.,
svnadmin create CSC300Repository
(Note - an easy "shortcut" for this step is to use Explorer to create the repository folder, then right-click on the
folder and choose "Open command window here" - a command prompt will be opened and you'll already be
"cd"ed to the correct folder.)
A plugin for Subversion is available for NetBeans (see Plugin note for details) - this plugin depends upon the
Subversion client (svn), which in turn depends on the Subversion server (svnadmin). Note that the NetBeans plugin
allows direct interaction with a Repository from within NetBeans via a GUI interface.
o svn can be used directly via the command-line - but there is no reason to do so, given the GUI plugin.
o the NetBeans plugin does not allow for Repository creation or administration - it is a GUI interface to svn, but
not to svnadmin or svnlook.
To IMPORT a project INTO the repository
o right-click the project in the project pane, slide down to Versioning, click on Import into Subversion Repository,
then follow the wizard's instructions.
► NOTE - the first time that a repository is referenced in a NetBeans installation, a path to the repository has to
be supplied, and there is NO BROWSE button, so the path has to be entered manually.
► For a local Repository reference (i.e., non-URL), the easiest solution - browse to the Repository folder in
Explorer, copy the full path, then paste it into the Repository URL area, then edit what was pasted so that it
contains the correct prefix and path separator characters, e.g., path might be:
D: \07-08JavaArchive\SubversionRepositories\TestRepository1\TestRep1
but the correct entry in the Repository URL area would HAVE to look like this:
file:///D: /07-08JavaArchive/SubversionRepositories/TestRepository1/TestRep1
Notice that all of the backslashes (\) had to be replaced with forward slashes (/), and then file:/// had to be
prepended to the front of the path.
► Importing can also be accomplished via Versioning-->Subversion-->Import into Repository, but this option
may not be available until at least one Repository has been "registered" with NetBeans (via the previous
steps).
To CHECK OUT a project FROM a repository
o Use Versioning-->Checkout..., then specify the Repository path/folder (via the dropdown list) that contains the
project to be checked out. Repositories that have been referenced previously are remembered; to access a "new"
Repository, supply the full path (details are the same as for importing a project into a repository).
o Within the Repository
► select the specific folder (project) that you want to check out
 a repository can contain multiple projects - make sure that you browse to the project that you are
interested in
► select the Revision of the folder (project) that you are interested in (use the Search button; click List to see
the available revisions) - the most recent revision (highest rev number) is usually the appropriate choice
Page 27 of 29
►
►

specify the folder where the checked-out project will be copied to your hard drive
life is a LOT simpler if an entire PROJECT is checked out, as opposed to individual file(s) - while the latter
is possible, and necessary for group projects, specifics regarding checkout and updating are too detailed to be
covered here.
► Leave the "Scan for NetBeans projects..." checked.
To update a project (to "check a project back into a repository")
o Update files (Save All, then Versioning-->Update Files). Note that this creates a virtual transaction - the
repository has NOT been physically updated yet!
o Commit files (Versioning-->Commit Files). This causes the updates to become a permanent part of the
Repository. Note that a message describing this revision is possible and is highly recommended. The net result of
"commit" is a new revision now being stored in the Repository.
Page 28 of 29
Screenshot of NetBeans IDE with a Java project open
Toolbar icons (note - tool button visibility varies based on customizations. To customize, right-click a blank area of the
toolbar and select Customize...):
(Left end) New File; New Project; Open Project; Save All; Undo; Redo
(Compile & Execute, starting with ) Build Main Project; Clean & Build Main Project; Debug Main Project; Profile
Main Project; Copy Path (to clipboard); Explore Path (opens Explorer); Shell on Path (command prompt)
(Quality & Testing, starting with ) Run PMD; Test Project (JUnit); Test File (JUnit); JUnit Test Results; Create test
skeleton JUnit; Memory Usage (click to force garbage collection)
Panes:
Upper Left: Project (used to switch between projects and to access specific project components)
Lower Left: Navigator (displays the components of whatever is in the Editor Pane)
Upper Right: Editor Pane (display a selected component. Tabs used to switch between open components)
Lower Right: Output Pane (displays results of project build, project execution, and other actions as appropriate)
Panes can be toggled visible via the Window menu item
A pane can be maximized (made to fill the screen) by double-clicking the tab; double-click again to restore the pane to
its original size and position.
To "undock" a pane, right-click its tab and choose "Undock Window"; to re-dock the pane, right-click its tab and choose
"Dock Window"
Project
Pane
Editor
Pane
Navigator
Pane
Output
Pane
Page 29 of 29