Instructor-Level Notes For Netbeans 6
Total Page:16
File Type:pdf, Size:1020Kb
NetBeans 6.1
User Guide
Version 1.1
2008-08-13
Copyright 2008 J. Kasprzyk, R. Briney, M. Brikman Preface
The purpose of this document is to present a "user's guide" to some of the more important features available in the NetBeans IDE (Integrated Development Environment). There are literally hundreds of features available - detailed information regarding the various options can be found in the documentation and FAQs available at www.netbeans.org.
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 time- consuming. To address this issue, some instructors create a "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 many 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 30 Table of Contents
Preface...... 2 Table of Contents...... 3 Download and Installation Options...... 4 Before beginning Installation ...... 4 Definition of netbeansHome ...... 4 Download Sources ...... 4 Installation, Self-Extracting Installer...... 5 Un-installation of a Self-Extracting Installation...... 5 Installation, Platform-Independent Zip File From NetBeans.org...... 5 Un-installation of a Platform-Independent NetBeans installation...... 6 Installation, Platform-Independent Zip File From Instructor ...... 6 Un-installation of a Platform-Independent NetBeans installation...... 7 Special Instructions for using NetBeans in Salem State College Computer Science Department labs ...... 8 IDE configurations and settings...... 9 Default JDK ...... 9 RAM requirements ...... 9 Java Documentation Access ...... 9 Code Navigation Toolbar...... 10 Memory Usage / Garbage Collection...... 10 Main toolbar customization...... 10 JDK Management...... 10 Library Management...... 11 Java style and presentation rules customization...... 11 Project Creation and Execution...... 13 Creating a new project "from scratch" (no pre-existing Java code) ...... 13 Creating a new Project using pre-existing Java source code ...... 13 Project Execution...... 14 Project-level customizations and settings...... 16 Specifying JDK (Compiler) Options ...... 16 Specifying JVM (Runtime) Arguments ...... 16 Code editing and formatting...... 17 Java Source File Creation...... 17 Code Creation and Editing...... 17 Productivity Hints...... 18 Project Syntax Verification...... 19 Comment Folding ...... 19 Keyboard shortcuts / code templates...... 19 Javadoc - Coding and Generation of HTML-formatted documentation...... 21 JUnit - test case creation and execution...... 23 Plugins and Plugin Management...... 25 PMD...... 25 CodeCoverage...... 26 JavadocAnalyser...... 26 Subversion - source code management utility...... 28 Screenshot of NetBeans IDE with a Java project open...... 30
Page 3 of 30 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 active- scan 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 permit the task at hand and installation should complete normally.
Some of the NetBeans installation files mentioned in the following sections require 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:\Program Files\NetBeans6.1 In the context of Computer Science Department labs, the netbeansHome folder might be R:\NetBeans_6.1_GeneralUse 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:\Program Files\NetBeans6.1, netbeansHome\etc\netbeans.conf would "expand" to C:\Program Files\NetBeans6.1\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.
Download Sources Standard Installable. Standard downloads for NetBeans are available at www.netbeans.org - click the "Download NetBeans IDE" button.
Page 4 of 30 o The default download type is a self-extracting installable - download to your hard drive, double-click, and respond to the wizard. Installing NetBeans this way will place an entry for NetBeans in the StartPrograms list, and will "register" NetBeans with the Windows Registry. o Note that the NetBeans home page often offers "pre-release" versions of NetBeans - these releases are unstable and are not suitable for novice software developers o Check with your instructor as to the most appropriate "bundle". The "Complete" or "All" version is the recommended default. o Make sure that the current "Platform" choice is appropriate for your machine. o If a bundle other than "All" is initially installed, note that any components that are missing can be downloaded and installed at any time via the Plugin Manager. o Specific details for installation are provided via a link on the NetBeans.org download page. o Any downloads from www.netbeans.org will be likely to require a degree of post-installation customization in order to be maximally useful in an academic setting. If your instructor has specified that you download NetBeans from www.netbeans.org, your instructor may provide a specific list of customizations for you to apply. Standard Extraction. Another mechanism for "installing" NetBeans is to go to the download page and select "OS Independent Zip" for the Platform. This download is NOT a self-extracting installer - it is simply a Zip archive of files that can be extracted into any folder on a hard drive; no start menu items will be created, nor will Windows Registry be affected (eventual "uninstalling" takes place by simply deleting the NetBeans folder). Customized Extraction. Your instructor may "customize" a version of NetBeans in order to optimize its functionality for a specific course or project. In this case, TWO (2) zip archives will be made available (usually on the R: drive of the Computer Science Department server). The supplied archives will NOT be standard self-extracting installer - like the "OS Independent Zip" mentioned in the previous bullet, "installation" is via extracting the files into a folder. One of the archives will contain NetBeans software and pre-installed plugins; the other will contain user- specific configuration settings. It is very important to o note the specific path to the files as specified by your instructor, and o download and extract both files!!!
Installation, Self-Extracting Installer Double-click the downloaded file: an installation wizard will launch and walk you through the installation process. Aside from possibly redirecting the directory into which NetBeans is to be installed, the options presented by the wizard should be accepted "as is". Note that the default location of user-specific settings and information is userProfile\.netbeans\6.1
Un-installation of a Self-Extracting Installation Use the Add or Remove Programs option in Windows Control Panel
Installation, Platform-Independent Zip File From NetBeans.org Double-click the downloaded file: 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:\Program Files\NetBeans6.1), then allow the utility to extract the contents of the archive into the specified folder. This folder will henceforth be referred to as netbeansHome. Browse to the NetBeans executable file and create a shortcut on the desktop: o The target file is named netbeans.exe, found in netbeansHome\bin, e.g., C:\Program Files\NetBeans6.1\bin\netbeans.exe. o Right-click the file, drag it onto the desktop, release, and select "Create Shortcuts Here" from the context menu. o Rename the shortcut so that it is easily identified: right-click, choose rename, choose a simple name like NetBeans 6.1 IMPORTANT INFORMATION - LOCATION OF USER-SPECIFIC SETTINGS
Page 5 of 30 o If NetBeans was downloaded from www.netbeans.org, the default location for user-specific settings will be in the user profile, in a folder named .netbeans\6.1
Un-installation of a Platform-Independent NetBeans installation Using Windows Explorer, browse to netbeansHome and delete the folder. Then browse to the location where user- specific settings were stored (default location is the user profile, in a folder named .netbeans\6.1) and delete it also.
Installation, Platform-Independent Zip File From Instructor There will be two (2) files that were provided by your instructor to download, typically named NetBeans-Software-versionName.zip and NetBeans-PersonalSettings-versionName.zip. The file names may be extended in some cases, e.g., if -versionName is actually 6.1-GeneralUse NetBeans-Software-6.1-GeneralUse-2008-08-18.zip and NetBeans-PersonalSettings-6.1-GeneralUse-2008-08-18.zip. Be sure to use the files specified by your instructor : use the specific folder specified by your instructor to acquire the files! (See Download Sources, Customized Extraction for specific acquisition instructions.) The following three (3) steps need to be performed in order to set up the customized installation properly.
(1) To install NetBeansSoftware.zip: o Double-click NetBeans-Software-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:\Program Files\NetBeans-versionName), then allow the utility to extract the contents of the archive into the specified folder. This folder will henceforth be referred to as netbeansHome . o Browse to the NetBeans executable file and create a shortcut on the desktop: . The target file is named netbeans.exe, found in \bin of \netbeansHome, e.g., C:\Program Files\NetBeans-versionName\bin\netbeans.exe. . Right-click the file, drag it onto the desktop, release, and select "Create Shortcuts Here" from the context menu. o Rename the shortcut so that it is easily identified (right-click, choose rename, choose a simple name like NetBeans versionName or NetBeans CSC202J).
(2) To install NetBeansPersonalSettings.zip: o Double-click NetBeans-PersonalSettings-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 settings are to be stored (netbeansHome), then allow the utility to extract the contents of the archive into netbeansHome. A folder named NetBeansPersonalSettings should appear in netbeansHome. Within NetBeansPersonalSettings will appear one subfolder: this subfolder will henceforth be referred to as versionName. The complete path to this folder is thus netbeansHome\NetBeansPersonalSettings\versionName
(3) To force NetBeans to use your personal settings by default: o Using Windows Explorer, browse to netbeansHome\etc\netbeans.conf, e.g., C:\Program Files\NetBeans-versionName\etc\netbeans.conf o Right-click the netbeans.conf file, "Open With" Wordpad (NOT WORD!), and insert the following instruction as the new first line of the file: netbeans_default_userdir="netbeansHome\NetBeansPersonalSettings\versionName" e.g., netbeans_default_userdir= "C:\Program Files\NetBeans-versionName\NetBeansPersonalSettings\versionName"
Page 6 of 30 The preceding instruction must be typed on a single line. Spaces matter (there's only one, between "Program" and "Files")! It is very important to copy the instruction exactly as it is presented above, including the double quotes. o Save the file, then close Wordpad.
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, e.g., C:\Program Files\NetBeans-versionName \NetBeansPersonalSettings\versionName o Note that on Computer Science Department lab computers, the default location for personal settings is H:\NetBeansPersonalSettings\versionName
Un-installation of a Platform-Independent NetBeans installation Using Windows Explorer, browse to netbeansHome and delete the folder. If the ..\versionName folder was stored outside of netbeansHome, browse to that folder and delete it also.
Page 7 of 30 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.1 or R:\NetBeans-6.1-GeneralUse\NetBeans6.1). This location will be referred to as netbeansHome in the following steps 1 through 3.
NetBeans setup tasks for Computer Science Department labs
(1) Using Windows Explorer, browse to netbeansHome\bin\netbeans.exe. Right-click and drag netbeans.exe onto a blank area of the desktop, then select Create shortcut here from the context menu. In the future, you will use this shortcut to launch NetBeans, but don't use it yet - the remaining steps must be completed before your initial execution of NetBeans!
(2) 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 in the next step as versionName. Copy the netbeansHome\NetBeansPersonalSettings folder to the root of your H: drive. You have just copied essential information regarding the NetBeans installation onto your private storage area of a server drive, where it will be referenced when you launch and use NetBeans. You can verify that you have copied correctly by using Windows Explorer to browse to H: - you should see a folder named NetBeansPersonalSettings. Opening H:\NetBeansPersonalSettings should reveal a folder named versionName.
(3) Demonstrate that you accomplished the preceding steps correctly by launching 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 something else appears in the Userdir entry, please see your instructor for assistance.
Page 8 of 30 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. o Note that JDKs do NOT come with docs "bundled" - don't forget to download JDK javadocs and extract them into the JDKs "doc" folder. o Note - when dealing with Computer Science Department lab computers, new JDKs will always have appropriate Javadocs installed To change the default JDK, launch NetBeans and check if the desired JDK is already registered with NetBeans as a Java platform (ToolsJava Platforms); add the JDK via the "Add Platform" button if it isn't listed. Close NetBeans. In the installation folder for NetBeans (referred to as netbeansHome), locate the following file: netbeansHome\etc\netbeans.conf, e.g., C:\Program Files\netbeans 6.1\etc\netbeans.conf. Open the file using a text editor (right-click, choose "Open With" WordPad, NOT WORD!). The line to be edited is netbeans_jdkhome="C:\Program Files\Java\jdk1.6.0_07" Change the value in quotes as appropriate to point to the JDK folder that you wish NetBeans to use by default.
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:\Program Files\netbeans 6.1\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 -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m to -J-Xss2m -J-Xms256m -J-XX:PermSize=256m -J-XX:MaxPermSize=512m . The numbers can be increased even higher if desired AND there is sufficient RAM available, but the suggested increased values should be sufficient for even very large projects. o Note that the "netbeans_default_options" is very long - use the scroll bar to locate the section of test to be changed, and do not insert any line feeds to improve readability - doing so will render the line meaningless to NetBeans.
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. . Use ToolsOptions, 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!
Page 9 of 30 . 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. o Note that if you have installed a version of NetBeans customized and supplied by your instructor, this step may have been performed already. You can check by hitting FI while the cursor is on a keyword - if Java documentation pops up, then this step has already been performed.
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 tool bar - 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 button bar can be customized by right-clicking in an empty area of the button bar 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 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 ToolsJava Platform Manager: this will launch the Java Platform Manager Wizard.
o To add a new JDK, click Add Platform o 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. o 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. o 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 ToolsJava 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.
Page 10 of 30 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 ToolsLibraries 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.
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 repeatedly clicking Add Project in the Project Properties window. 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 is 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 ToolsOptions: this will launch the Options window. 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)
Page 11 of 30 ► In the area labeled Code Completion, check Auto Popup Completion Window, Case Sensitive Code Completion, Insert Closing Brackets Automatically, and Show Deprecated Members ► In the Camel Case Behavior area, check Enable Camel Case Navigation . Click the Indentation tab. ► Check the "Expand Tabs to Spaces" option ► Set Number of Spaces per Indent to 4 unless your instructor indicates otherwise ► Set the right margin to 100 o In the top row of Options click Java Code . Click the Formatting tab ► Select Indents in the Category area; set Continuation Indentation Size to 2, then check the Indent Top Level Class Members and Indent Case Statements in Switch ► Select Alignment and Braces in the Category area . In the Braces Placement tab, set all options to "New Line", then check Special "else if" Treatment . In the Braces Generation tab, set all options to "Generate" . In the New Lines tab, check all options EXCEPT "after modifiers" o Click OK to save the settings
Page 12 of 30 Project Creation and Execution
Creating a new project "from scratch" (no pre-existing Java code) FileNew 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. . Note that the project location that you choose is automatically pre-pended onto the name of your project in the Project Folder text area. 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, then 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 Creating a new project from existing code requires the following actions: o Create an empty project using NetBean's wizard (see Creating a new project "from scratch") . In most cases the "Create Main Class" option should be de-selected - check with your instructor o Close the project o Using Windows Explorer, Copy (not move!) files from wherever they are available into the project's src folder, taking care to preserve package structure o In NetBeans, open the project - the copied files should now appear in the project pane, from where they can be opened
The details of how to accomplish these steps follow below.
Note: it bears explicit and repeated mentioning that when creating a new project based on existing code, the files that are to be used in the new project should be copied into the new project.
Create a new project (see Creating a new project "from scratch")
Close the new project
Launch Windows Explorer and use it to locate the files that are to be incorporated in the new project and to copy those files into the new project. o All Java source files should be copied (not moved!) into a subfolder of the src folder of the project that was just created (e.g., ...\NewProjectName\src\...) Page 13 of 30 o 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 NewFolder, then editing the name of the new folder. o Note that any files that are to be copied that are not Java source files must be placed somewhere in the project other than the src folder or its subfolders. Any file in the src folder hierarchy may be assumed by the Java compiler to be a Java source file and could be compiled when a Build is performed - any non-Java files in the src folder hierarchy may therefore generate numerous errors messages. o Close or minimize Windows Explorer
In NetBeans re-open the new project (FileOpen Recent Project) o Verify that the Java source files that were copied are visible to the project: expand the project in the project pane, then expand Source Packages (which represents the src folder), then expand each subfolder in turn, making sure that all of the necessary files are present. If a file or two was omitted, close the project, return to Explorer, make the copies, then re-open the project and re-verify. o If not taken care of when the project was created, 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.
Project Execution RunRun Main Project 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; the Run MainProject button on the Toolbar is another way of accomplishing this task, as is F6. If there are any syntax errors, this option behaves the same way as the Build Project option in the section Code Editing, section Project Syntax Verification. Output will appear in the output pane o NetBeans will initially display the results of preparing the project for execution, followed by any output, followed by a "Build Successful" message.
init: deps-jar: Compiling 3 source files to H:\JavaProjects\HelloWorld\build\classes compile: run: 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:
init: deps-jar: Compiling 1 source file to H:\JavaProjects\HelloWorld\build\classes compile: run: Exception in thread "main" java.lang.NullPointerException at junk.Main.main(Main.java:30) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)
Page 14 of 30 o Correcting a runtime error is done the same way as correcting a syntax error - click the link to see 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 time-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 15 of 30 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
Page 16 of 30 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. FileNew 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. Unless otherwise instructed, 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. . 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), 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, and only then open the source file via NetBeans. 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. 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.
Page 17 of 30 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 (4th button from the left in the toolbar).
Many IDEs automatically make "archive" copies of files as changes are made, thus providing a crude form of backup. NetBeans does not make archive copies - if you accidentally damage or destroy a file, the file is not recoverable as it might be in other IDEs.
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 WindowNavigatingNavigator). 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 Code) - 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" 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. Page 18 of 30 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. BuildBuild 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 (BuildClean 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). The outcome of the build will appear 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 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. o 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. o It bears mentioning that with experience, determining the actual cause of a syntax error is usually straightforward.
Comment Folding ToolsOptionsEditor 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 //
Page 20 of 30 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 right- clicking 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. 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.1). 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/build- impl.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 and which must remain after your insertion):
overview="ProjectOverview.html" doctitle="Overview of ThreadedSearch Example Project" header="ThreadedSearch Example Project" linksource="true" stylesheetfile="notes/TweakedCSSJavadocStyleSheet.css" >
Page 22 of 30 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 custom- implemented 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.1 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 ToolsCreate JUnit Tests. . 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, ToolsCreate 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 ToolsCreate 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 time- saver. 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 23 of 30 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
Page 24 of 30 Plugins and Plugin Management
Plugins are managed via ToolsPlugins Settings contains a list of Update Centers that NetBeans will periodically check for updates and new plugins. o A few that are not included in the default NetBeans configuration that are of interest are: . 3rd party plugins: http://updates.netbeans.org/netbeans/updates/6.0/uc/final/thirdparty/catalog.xml.gz . Plugin Portal: http://plugins.netbeans.org/nbpluginportal/updates/6.0/catalog.xml.gz . SQE Update Center: https://sqe.dev.java.net/updatecenters/sqe/updates.xml . NetBeans Beta: http://updates.netbeans.org/netbeans/updates/6.0/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 (ToolsModule Manager, then expand the4 Base IDE entry).
A few plugins in particular are very useful in promoting good code style and in pointing out possible problem areas:
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 execution (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 . 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.
Page 25 of 30 . After downloading the plugin, use ToolsPlugin, click the Downloaded tab, click Add Plugins, browse to the downloaded file, click Open, then click Install. o To execute PMD, use QualityCode DefectsRun PMD, or use the PMD button in the main button bar: this will produce a report in the output pane that details PMD violations. o 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. o To observe and activate/deactivate the rules that PMD will evaluate (the "active" rules), use ToolsOptionsQuality, 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, 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. o Note that changes to the list of active rules are not immediately applied to an open project - PMD must be re- executed in order to see the affects of the changes. o 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 (right- click 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 re- opened. ► 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. ► 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.
Page 26 of 30 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 SourceAnalyze Javadoc. If the resulting Analyzer Window is accidentally closed, it can be opened via WindowAnalyzer.
Page 27 of 30 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
Page 28 of 30 ► 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 ► 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 29 of 30
Screenshot of NetBeans IDE with a Java project open
Toolbar icons (note - tool button visibility varies based on customizations!): (Left end) New File; New Project; Open Project; Save All; Cut; Copy; Paste; Paste History; Undo (Starting with the hammer) Build Main Project; Clean and Build Main Project; Run Main Project; Test Project; Test File; Create JUnit skeleton; Debug Main Project
Panes: Upper Left: Project (used to switch between projects and to access specific project components) Middle Left: Navigator (displays the components of whatever is in the Editor Pane) Right: Editor Pane (display a selected component. Tabs used to switch between open components) Bottom: 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 Navigato r Pane
Output Pane
Page 30 of 30