manual oficial netbeans 3.6

58
8/20/2019 Manual Oficial Netbeans 3.6 http://slidepdf.com/reader/full/manual-oficial-netbeans-36 1/58 Using NetBeans TM  IDE 3.6 Feedback  Your Guide to Getting Work Done in NetBeans IDE Welcome to the Using NetBeans TM  IDE 3.6 guide. This guide is designed to give you a more detailed introduction to the IDE than available in the Getting Started tutorial. Various aspects of the IDE are explored in detail. This guide is geared mostly for newcomers to NetBeans IDE, whether they are new to Java, new to using IDEs, or experienced IDE users that are switching over from a different IDE. This guide covers the following:  Setting Up Your Project  Basic IDE Concepts  The Filesystems Window  Projects in the IDE  Accessing Source Directories  Filesystems and the Java Classpath  Correctly Mounting Java Packages  Mounting Resource Libraries  Advanced Project Setup  Creating and Editing Java Source Code  Creating Java Files  GUI Templates and Java Templates  Editing Java Files in the Source Editor  Using Abbreviations, Word Matching, and Code Completion  Configuring Code Completion  Adding Fields, Bean Properties, and Event Listeners  Working With Import Statements  Search and Selection Tools  Formatting Java Source Code  Navigating Between Documents  Configuring the Editor Page 1 of 58

Upload: charlie21993

Post on 07-Aug-2018

229 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 1/58

Using NetBeansTM

 IDE 3.6

Feedback

 Your Guide to Getting Work Done in NetBeans IDE

Welcome to the Using NetBeansTM

 IDE 3.6 guide. This guide is designed togive you a more detailed introduction to the IDE than available in theGetting Started tutorial. Various aspects of the IDE are explored in detail.This guide is geared mostly for newcomers to NetBeans IDE, whether theyare new to Java, new to using IDEs, or experienced IDE users that areswitching over from a different IDE.

This guide covers the following:

  Setting Up Your Project 

  Basic IDE Concepts

  The Filesystems Window

  Projects in the IDE

  Accessing Source Directories 

  Filesystems and the Java Classpath

  Correctly Mounting Java Packages

  Mounting Resource Libraries  Advanced Project Setup

  Creating and Editing Java Source Code 

  Creating Java Files 

  GUI Templates and Java Templates

  Editing Java Files in the Source Editor 

  Using Abbreviations, Word Matching, and Code 

Completion

  Configuring Code Completion

 

Adding Fields, Bean Properties, and Event Listeners

  Working With Import Statements

  Search and Selection Tools

  Formatting Java Source Code

  Navigating Between Documents

  Configuring the Editor

Page 1 of 58

Page 2: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 2/58

  Compiling Java Programs 

  Compiling Files

  Working with Compiler Types 

  Specifying the Compiler Type for Files and Projects

  Creating Custom Compiler Types

  Setting the Target Directory for .class Files

  Cross-Compiling Between Java Platforms

  Using JavaMake to Manage Class Dependencies

  Debugging Java Programs 

  Basic Debugging 

  Starting a Debugging Session

  Debugger Windows

  Stepping Through Your Code

  Working With Breakpoints 

  Setting a Breakpoint

  Setting Conditions for Breakpoint

  Customizing the Output for a Breakpoint

  Breakpoint Types

  Setting Watches

  Packaging and Deploying Your Applications 

  Creating a JAR File 

  Creating a JAR Recipe

  Compiling and Creating the JAR File  Mounting and Checking the JAR File

  Modifying a JAR File 

  Adding Files to a JAR Recipe

  Modifying the Manifest File

  Setting the JAR Content Filter

  Executing a JAR File

  Using Javadoc 

  Integrating Java API Documentation into the IDE 

  Making Javadoc Documentation Available in the IDE

  Searching and Displaying Javadoc Documentation

  Configuring the External Browser to Display 

Javadoc Files

  Adding Javadoc Comments to Your Code

  Generating Javadoc Documentation 

Page 2 of 58

Page 3: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 3/58

  Specifying an Output Directory for Javadoc Files

  Team Development With CVS 

  Checking Out Sources

  Mounting a CVS Filesystem

  Specifying Advanced Command Options

  Configuring a CVS Filesystem

  Setting the Relative Mount Point

  Shortening and Hiding File Status

  Working With CVS Files

  Using the Graphical Diff Tool

  Creating and Applying Patches

  Resolving Merge Conflicts Graphically

  Making Safe Commits

  Configuring the IDE   Setting IDE Default Settings 

  Configuring IDE Startup Switches

  Configuring General Java Settings

  Working with Unknown File Types 

  Enabling and Disabling IDE Functionality 

  Disabling Modules

  Installing New Modules from the Update Center

  Boosting NetBeans Performance 

  Tuning JVM Switches for Performance

Page 3 of 58

Page 4: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 4/58

Setting Up Your Project

Using NetBeans IDE 3.6Previous - TOC - Next

Feedback

This section covers the basics of

correctly setting up your IDE tostart developing your projects.The process of managing projectcontents and properties is centered around the Filesystems window. Themost common tasks in setting up a project are adding source files to theproject, making resource libraries available to the project, correctly settingup the Java classpath, and configuring output directories for compiledclasses and Javadoc documentation.

This section covers:

  Basic IDE Concepts - The Filesystems window and working with

projects.  Accessing Source Directories - Adding source files and directories

to a project, understanding filesystems, configuring the Javaclasspath, correctly mounting Java packages, and making classlibraries (JAR files) available to the project.

  Advanced Project Setup - An example of a more advanced IDE

project with two separate output directories for compiled classes andone for Javadoc documentation.

Basic IDE Concepts

Before you start setting up your project, let's take a minute to getacquainted with some of the basic concepts involved with using the IDE.

The Filesystems Window

Page 4 of 58

Page 5: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 5/58

The startingpoint fordevelopmentin the IDE is

theFilesystemswindow. TheFilesystemswindow iswhere youorganizeyour projectcontents,access andruncommandson individualfiles, andview thestructure ofyour sourcefiles. TheFilesystemswindowcontains all

of thedirectories,packages,and archivefiles thatyou haveadded toyour project.

When you first run the IDE, the Filesystems window contains the NetBeans

sample directory with some sample code. Each source file has its ownFilesystems window node. These nodes have:

  Contextual Menu Commands - You can run commands on files byright-clicking them and choosing from the contextual menu. Thecommands that are available vary depending on the type of node youare working with.

  Properties - Choose Window > Properties (Ctrl-1) to open a context-

Page 5 of 58

Page 6: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 6/58

sensitive Properties window. The Properties window always shows theproperties of the component in the NetBeans user interface that hasthe focus. If you want to open a persistent Properties window thatonly shows the properties of one Filesystems window node, right-click

the node and choose Properties.If a property contains an ellipsis button (...), you can click the buttonto access a special property editors that you can use to defineproperties visually.

  Subnodes - You can expand most nodes in the Filesystems windowto view subnodes representing the internl structure of the node's file.These subnodes often have their own properties and contextual menucommands.

The Filesystems window does not show a node for every file in a mounted

directory. For example, for the compiled ColorPicker form object, the sourcedirectory contains the ColorPicker.java source file, the ColorPicker.

form file used to build its GUI in the IDE, and the ColorPicker.class 

compiled class. The IDE hides .form and .class files by default, so only

one node is shown for ColorPicker. You can also choose to hide files by typeand extension.

Projects in the IDE

A project is the basic unit of work in the IDE. It includes all the files withwhich you are working and the IDE settings that you apply to those files.The NetBeans IDE has a very straightforward projects system. You alwayshave one project open at a time. Everything that is in the Filesystemswindow is part of the currently open project. You add directories and files tothe project by mounting them as filesystems in the Filesystems window.

Note: You do not have to create a new project for each application you areworking on. You can add the source files for multiple applications to theFilesystems window and work on them at once. Each project, however, hasonly one classpath and set of IDE settings. 

Most IDE settings are applied at one of two levels: for the whole project orfor individual files. Project-wide settings are managed in the Optionswindow. You can open the Options window by choosing Tools > Options inthe Main window. You configure settings on a file using the Propertieswindow.

Page 6 of 58

Page 7: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 7/58

When you open the IDE, the default project opens with some sample sourcemounted in the Filesystems window. If you do not need the examples, youcan remove the sample filesystem by right-clicking the filesystem node andchoosing Unmount Filesystem. You can also create an empty project by

choosing Project > Project Manager and clicking the New button.

Accessing Source Directories

As mentioned before, you access source directories and files in the IDE bymounting them in the Filesystems window. To mount a local directory as afilesystem, go to the Filesystems window, right-click the root Filesystems

node ( ) and choose Mount > Local Directory.

Each project also contains some hidden filesystems that are added by theIDE. These filesystems contain the JDK sources which you can view indebugging sessions, common Java libraries, and Javadoc documentationlibraries. You can view all of the filesystems in your project by right-clickingthe root Filesystems node and choosing Customize.

Note: If the sources you are working with are under version control, youcan mount them as a VCS filesystem. VCS filesystems let you see files'versioning status and run VCS commands right in the Filesystems window.For more information, see Team Development With CVS .

Filesystems and the Java Classpath

Mounting filesystems not only defines the contents of a project, it alsodefines the Java classpath for the project. Unlike in command-linedevelopment, the IDE ignores the CLASSPATH variable on your system andbuilds a unique internal classpath for each of your projects. This classpath is

Page 7 of 58

Page 8: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 8/58

made up of all the mountedfilesystems, includinghidden filesystems andfilesystems that are

mounted by default by theIDE.

Note: You can view all of a project's filesystems,including hiddenfilesystems, by right-clicking the root Filesystemsnode and choosingCustomize. 

In general, whenever youwant to add something to the classpath, you should mount it in theFilesystems window. This includes Java libraries (JAR files) that your codedepends on (see Mounting Resource Libraries). You can also customize

the classpath for various operations, like running, compiling, anddebugging, using the filesystem's property sheet. Go to the filesystem'sproperty sheet and set the Capabilities properties accordingly. For example,you should exclude filesystems that only contain Javadoc documentationfrom the classpath for running, compiling, and executing.

In addition to building the classpath, mounting files in the Filesystemswindow also makes them available for other IDE tools such as codecompletion.

Correctly Mounting Java Packages

Directories that contain Java source code must be mounted at the packageroot, which is the directory that contains the default package. The sourcesin the directories must be in packages corresponding to their positionrelative to the mount point. If a filesystem of Java sources is mounted atthe wrong point, your source code will contain error markers in the SourceEditor and will not compile.

Page 8 of 58

Page 9: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 9/58

If you have multiple source trees with thepackage root of each tree groupedtogether under one directory, you have tomount each package root separately. For

example, in the directory structurepictured on the right, src is the package

root for the class com.myapp.MyApp.java 

and lib is the package root for the class

com.mylib.MyLib.java. In this example,

you cannot simply mount MyProject - youhave to mount src and lib separately.

You can add more than one directory at a time by holding down the Controlkey and selecting multiple directories in the Mount wizard.

Mounting Resource Libraries

If your code depends on any resource libraries, you have to mount thelibraries in order to add them to the project's Java classpath. Resourcelibraries can be contained in regular directories or, more commonly, in JARfiles. You can mount a JAR file as a filesystem in the IDE by right-clickingthe root filesystem node and choosing Mount > Archive File. Mounting aresource library also makes all of its contents available for code completion.

If you do not need to browse through the files in your resource library, youcan hide the filesystem by setting its Hidden property to True.

Note: You can display a hidden filesystem by right-clicking the rootFilesystems node and choosing Customize. In the customizer, select thehidden filesystem and set its Hidden property to False.

Advanced Project Setup

Now let's look at a more complicated project structure and how to mount it

correctly in the IDE. We will be discussing a few concepts we haven't goneover yet, but you can use the links in the text to jump ahead to anysections that you are not clear about.

Here is the structure of our project:

MyProject

Page 9 of 58

Page 10: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 10/58

  myApp  src // contains sources for myApp  lib // contains binary libraries (JAR files) used by myApp  myLib

  src // sources for a library used by myApp and otherapplications  lib // contains binary libraries (JAR files) used by myLib  build  myApp // output dir for compiled classes for myApp  myLib // output dir for compiled classes for myLib  lib // contains binary libraries (JAR files) used by bothmyApp and myLib

  doc // contains generated Javadoc for the project

First, mount the myApp/src and myLib/src directories as separatefilesystems. These are our main development directories - except for thedoc directory, they will be the only filesystems that are visible in our

Filesystems window when we are done setting up our project.

Next, mount the output directories for our classes, build/myApp and build/

myLib, as separate filesystems. There is no reason to keep the output

directories visible in the Filesystems window, since you can execute filesfrom their source nodes in the development directories. Hide the filesystemsby setting their Hidden property to True.

Now let's set up the compiler types that will place the compiled classes formyApp and myLib in the correct build directories. First, go to the Options

Window and make a copy of External Compilation called myApp

Compilation. To set this compiler type to store compiled classes in thebuild/myApp directory, set the compiler type's Target property to build/

myApp. Then create another copy of External Compilation called myLib

Compilation and set its Target property to build/myLib.

Now we are ready to assign our custom compiler types to the sources in our

source tree. This is a bit tricky, since you cannot just select a filesystem orgroup of files in the Filesystems window and set the Compiler property forall of them. Instead, we will search for all Java objects in each filesystemand assign the compiler type from the Search Results window.

First, choose Window > Properties (Ctrl-1) to open the Properties window.Then right-click the myApp/src filesystem and choose Find. Click the Type

Page 10 of 58

Page 11: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 11/58

tab and select Java Source Objects, then click Search. The Search Resultswindow returns all the Java source files in myApp/src. Select all of thesources, then in the Properties window set the Compiler property to myAppCompilation. Follow the same process to assign myLib Compilation to all the

Java sources in myLib/scr.

Next we can set up our Javadoc output directory. Mount the doc directoryas a filesystem. In the filesystem's property sheet, set the Use in Execution,Use in Compiler, and Use in Debugger properties to False and set the Use asDocumentation property to True. Then go to the Options window and setthe IDE to use it as the default Javadoc output directory for the

project. The directory will then house all of the Javadoc documentation yougenerate for the source you are developing. This documentation will also beavailable for Javadoc index searches in the IDE.

Finally, mount your resource libraries in the Filesystems window. In ourexample, the libraries are stored in JAR files throughout our source tree, soyou have to mount them with the Mount > Archive File command. If you donot need to browse through the code in these libraries, hide the filesystemsso that they do not clutter up your Filesystems window.

Previous - TOC - Next

Page 11 of 58

Page 12: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 12/58

Creating and Editing Java Source Code

Using NetBeans IDE 3.6Previous - TOC - Next

Feedback

Creating and editing Java source code is the mostimportant function that the IDE serves. After all, that'sprobably what you spend most of your day doing. NetBeansIDE provides a wide range of tools that can compliment any

developer's personal style, whether you prefer to code everything by hand or want the IDE togenerate large chunks of code for you.

This section covers the following topics:

  Creating Java files - Using the New wizard and the IDE's templates to create new files, GUI

form templates versus Java source templates.  Editing Java files in the Source Editor - Using code completion and abbreviations,

generating bean properties and event listeners, working with import statements, search andselection tools, and formatting Java code.

  Navigating between documents - switching between open files, cloning the view of a file,

and splitting the Source Editor.  Configuring the Source Editor - customizing the Source Editor to fit your development style.

Creating Java Files

NetBeans IDE contains templates and wizards that you can use to create all kinds of source files,from Java source files to XML documents and resource bundles.

The easiest way to create a file is to right-click the directorynode in the Filesystem window where you want to createthe file and choose from the New submenu in the node'scontextual menu. The New submenu contains shortcuts tocommonly-used templates and an All Templates command

that you can use to choose from all NetBeans templates.

To demonstrate some of the IDE's source creation andediting features, let's recreate the ColorPreview class thatcomes with the colorpicker example in the IDE's samplecode. Right-click any directory in your mounted filesystems and choose New > Java Class. Name thefile ColorPreview and click Finish. The file opens in the Source Editor.

GUI Templates and Java Templates

If you want to visually edit a Java GUI form using the Form Editor, you have to create the form'ssource file using the IDE's Java GUI Forms templates. This template group contains templates forAWT and SWING forms. For example, you cannot create a normal Java class file and then change itto extend JPanel and edit it in the Form Editor. The form must be created from the JPanel template.

Editing Java Files in the Source Editor

The Source Editor is your main tool for editing source code. It provides a wide range of features thatmake writing code simpler and quicker, like code completion, highlighting of compilation errors,syntax highlighting of code elements, and advanced formatting and search features.

Page 12 of 58

Page 13: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 13/58

Although we talk about the Source Editor as one component, it is really a collection of editors. Eachtype of source file has its own editor that provides different functionality. In this section we'll bedealing with the Java editor, but many of the same concepts apply to other editors.

To open a Java source file in the Source Editor, double-click the file's node in the Filesystemswindow.

Note: Double-clicking a Java form node ( ) in the Filesystems opens two tabs in the Source Editor:a source tab containing the Java source code for the form, and a Form Editor tab showing the design-time view of the form. To edit the source code for a Java form without opening the Form Editor, right-click its node and choose Edit.

Using Abbreviations, Word Matching, and Code Completion

The Source Editor provides many features that spare you from having to enter long Java class namesand expressions by hand. The most commonly used of these features are abbreviations, codecompletion, and word matching.

Code completion in the Java SourceEditor lets you type a fewcharacters and then choose from alist of possible classes, methods,variables, and so on toautomatically complete theexpression. The Source Editor alsoincludes a Javadoc preview windowthat displays the Javadocdocumentation for the currentselection in the code completionbox, if any exists. The Javadoc isdrawn from the compiled source

files mounted in the IDE.

Abbreviations are short groups ofcharacters that expand into a fullword or phrase when you press thespace bar. For example, if you enterpsfs and press the space bar, it expands into public static final String. For a full list of theIDE's default abbreviations, click here.

You can also add your own custom abbreviations for each type of editor. In the Options window,select Editing > Editor Settings > Java Editor and open the property editor for the Abbreviationsproperty. You can use the Abbreviations property editor to add, remove, and edit the abbreviations

for Java files.

Word matching is a feature that lets you type a few characters of a word that appears elsewhere inyour code and then have the Source Editor generate the rest of the word. Type a few characters andpress Ctrl-L to generate the next matching word or Ctrl-K to generate the previous matching word.

As a quick exercise, let's make ColorPreview extend JPanel. Put the insertion point afterColorPicker in the class declaration, then type ex and press the space bar to expand theabbreviation into extends. Then type the first few letters of javax. The code completion box shouldpop up after a few seconds. If it does not, you can always manually open it by pressing Ctrl-Space.

Page 13 of 58

Page 14: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 14/58

Use the code completion box to enter javax.swing.JPanel.

Configuring Code Completion

The IDE maintains a code completion database which it uses to provide suggestions for code

completion and other features. The code completion database contains classes from the J2SK version1.4, other commonly used APIs like the Servlet and XML APIs, and the sources in all of thefilesystems you have mounted in your project. Whenever you mount a filesystem, the IDEautomatically adds all of the filesystem's public and protected classes to the project's codecompletion database. You can also right-click the filesystem and choose Tools > Update CodeCompletions to configure which of the filesystem's classes are available for code completion.

In the Options window, you can disable and enable code completion and set the length of the pausebefore the code completion box appears in the Source Editor. Select Editing > Editor Settings > JavaEditor and set the Auto Popup Completion Window property and the Delay of Completion WindowAuto Popup property accordingly.

You can also turn off the Javadoc preview box for code completion. Select Java Editor and uncheck

the Auto Popup Javadoc Window property.

Adding Fields, Bean Properties, and Event Listeners

Even if you prefer to write your code the old-fashioned way, the NetBeans Java editor has some coolcode generation features that you may find handy, especially when dealing with bean properties andevent listeners.

Let's start by adding some of the fields for our colors in ColorPreview. Go to the first line after theclass declaration and type in the following code:

  private int red;

Now let's turn this ordinary field into a bean property by making some getter and setter methods forit. Right-click anywhere in the field declaration and choose Tools > Generate R/W Property for Field.The following code is generated in the file:

  public int getRed() {  return red;

  }

  public void setRed(int red) {  this.red = red;

  }

The methods now show up under the Methods node. The Bean Patterns node now also contains abean property node for red.

Now let's add both the field and the get and set methods at the same time. In the Filesystemswindow, right-click the Bean Patterns node for ColorPreview and choose Add > Property. In thedialog, enter green for the name and int for the type, then check Generate Field, Generate GetMethod, and Generate Set Method and click OK. The following code is added to the file:

  private int green;

Page 14 of 58

Page 15: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 15/58

  public int getGreen() {  return this.green;

  }

  public void setGreen(int green) {

  this.green = green;  }

So far, so good. But to fully generate a working bean that can get and set the value of each of thecolor bean properties and notify the caller of its changes, we have to add event listeners to each ofthe set methods. There are two ways to do this. You could right-click the Bean Patterns node andchoose Add > Multicast Event Source to add the java.beans.propertyChangeListener  methods,then enter the rest of the source by hand.

An easier way is to generate all of the necessary code when you create the bean properties. First,let's get rid of all of the methods and fields we have created so far. You can do so by deleting thenodes from the Filesystems window or just by deleting the code in the Source Editor.

Next, right-click the Bean Patterns node and choose Add > Property. Enter red for the name, int forthe type, and select the Bound checkbox. Now you can set the dialog to generate not just the fieldand methods for the property, but also the property change support code. Click OK to generate thefollowing code in the Source Editor:

  private int red;

  private java.beans.PropertyChangeSupport propertyChangeSupport = new java.beans.

PropertyChangeSupport(this);

  public void addPropertyChangeListener(java.beans.PropertyChangeListener l) {

  propertyChangeSupport.addPropertyChangeListener(l);

  }

  public void removePropertyChangeListener(java.beans.PropertyChangeListener l) {

  propertyChangeSupport.removePropertyChangeListener(l);

  }

  public int getRed() {  return this.red;

  }

  public void setRed(int red) {

  int oldRed = this.red;  this.red = red;

  propertyChangeSupport.firePropertyChange("red", new Integer(oldRed), new

Integer(red));  }

Then all you have to do is repeat the process for the green and blue properties and change theColorPreview constructor to the following:

  public ColorPreview() {

  propertyChangeSupport = new java.beans.PropertyChangeSupport(this);

  }

Page 15 of 58

Page 16: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 16/58

And that's it! You've got a nice working bean ready to be used by the ColorPicker program.

Working With Import Statements

Whenever the IDE generates Java source code, it uses the fully qualified names for all the elements it

creates. There are two tools that you can use to add import statements to your code and changebetween simple names and fully qualified names: the Fast Import command and the ImportManagement Tool.

To use the Fast Import command, place the insertion point on any class name and press Alt-Shift-I.In the following dialog box, specify whether to import the class or the entire package.

Unfortunately, the Fast Import command does not change all fully qualified names for the class tosimple names. A more complete tool for handling import statements is the Import Management Tool(IMT). By default, the IMT changes all occurrences of fully qualified names into simple names andcreates a single-name import statement for each.

Right-click anywhere in the ColorPicker file in the Source Editor and choose Tools > Import

Management Tool. The first page of the IMT shows any unresolved identifiers in your file. These canoccur when you incorrectly enter the class name or when you are referencing code that you do nothave mounted in your project yet. You can enter a new package name to import for the classes, orimport the classes as they are written.

At this point, you can click Finish immediately to run the IMT with its default settings. You can alsoclick Next to further customize the tool's actions. For example, if you are importing several classesfrom a single package, you may want to import the entire package. You can do so on the RemovedUnused Imports page of the wizard. Change the Action column for the package from Use Single-Name Import to Use Package Import.

Page 16 of 58

Page 17: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 17/58

Search and Selection Tools

When you are dealing with a large group of files, the ability to quickly find, navigate to, and selectcertain strings or files is critical to your productivity. The following list gives you a quick overview ofthe search and selection tools that are available in the Source Editor:

KeyboardShortcut

Descriptionof Command

Ctrl-F Search for text in the currently selected file. The Source Editor jumps to thefirst occurrence of the string and highlights all matching strings. You can useF3 to jump to the next occurrence and Shift-F3 to jump to the previous.

Ctrl-H Replace text in the currently selected file.F3 Find the next occurrence of the word you searched for.

Shift-F3 Find the previous occurrence of the word you searched for.

Ctrl-F3 Search for the next occurrence of the word that the insertion point is on.

Alt-Shift-H Turn off search result highlighting.

Page 17 of 58

Page 18: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 18/58

Alt-Shift-O Open the Fast Open dialog box, which lets you quickly open a file. Start typinga class name in the dialog box. As you type, all files that match the typedprefix are shown. The list of files is generated from the the project's mountedfilesystems.

Alt-O Go to source. This shortcut opens the file where the item at the insertion point

is defined.

Alt-G Go to declaration. Similar to the previous shortcut, this opens the file wherethe variable at the insertion point is declared.

Ctrl-G Go to line. Enter any line number for the current file and press Enter to jumpto that line.

Ctrl-F2 Add a bookmark ( ) to the line of code that the insertion point is currently

on. If the line already contains a bookmark, this command removes thebookmark.

F2 Go to the next bookmark.

Alt-L Go to the next location in the jump list for the currently selected file. The jump list is a history of all locations where you made modifications in theEditor.

Alt-K Go to the previous location in the jump list for the currently selected file.

Alt-Shift-L Go to the next jump list location in all files (not the currently selected file).

Alt-Shift-K Go to the previous jump list location in all files.

Formatting Java Source Code

The IDE automatically formats your code as you write it. You can automatically reformat specific linesof code or entire files. The following table lists some common formatting commands.

KeyboardShortcut

Descriptionof Command

Ctrl-Shift-F Reformat the entire file or whatever text is selected in the Source Editor.

Ctrl-T Shift the current line or selection one tab to the right.

Ctrl-D Shift the current line or selection one tab to the left.

Ctrl-E Remove the current line.

Ctrl-Shift-T Comment out the current line or all selected lines with line comments ("//").

Ctrl-Shift-D Remove comments. This command only works for lines that begin with linecomments ("//").

Navigating Between Documents

The Source Editor makes it easy to manage large number of open documents at one time. TheSource Editor displays a row of tabs for open documents. The tabs appear in the order in which youopened the documents. You can grab any tab and drag it along the row of tabs to move its position.Use the left and right buttons in the top-right corner to scroll through the row of tabs.

Page 18 of 58

Page 19: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 19/58

To switch between open files, do any of the following:

  Use the drop down list at the top-right of Source Editor. The drop down list displays all of youropen files in alphabetical order.

  Press Alt-Left and Alt-Right to move one editor tab to the left or right.  Press Ctrl-` to open the IDE window manager, which contains icons for each open document in

the Source Editor as well as all open windows like the Filesystems window.

You can also:

  Maximize the Source Editor. Double-click any document tab or press Shift-Escape to hide allother IDE windows. If you have split the Source Editor, only the partition you maximize isdisplayed.

  Clone a document. Right-click the document in the Source Editor and choose CloneDocument.

  Split the Source Editor. Grabbing any document tab and drag it to the left or bottom marginof the Source Editor. A red box shows you where the new Source Editor partition will resideonce you drop the document. Any Source Editor partition can also be split any number of times.

  Move documents between Source Editor partitions. Grab the document tab and drag it tothe row of tabs in the destination partition.

Configuring the Editor

To configure Source Editor settings, open the Options window and expand Editing > Editor Settings.The Editor Settings node has subnodes for the editors used for each different file type. In thissection, we will be looking at configuring the Java editor, but many of the settings are the same forall editors.

Here is a quick overview of some of the more common customizations to the Source Editor:

  View or change abbreviations. Open the property editor for the Abbreviations property andmake any changes to the list.  View or change all keyboard shortcuts for the IDE. Open the property editor for the Key

Bindings property.  View or change all recorded macros. Open the property editor for the Key Bindings

property.  Turn off code completion. Set the Auto Popup Completion Window property to False.  Set the font size and color for code. Use the Font Size property to quickly change the font

size for all Java code in the Source Editor. Open the property editor for Fonts and Colors tochange the font and color of each type of Java code, like method names or strings.

  Change the indentation used in your code. You can switch between indentation engines bychoosing a new engine from the Indentation Engine property. You can also configure eachindentation engine by opening the property editor for the property.

  Set how many spaces are inserted for each tab in your code. Set the Tab Size propertyaccordingly.

  Turn off Javadoc for code completion. Go to the Expert tab and set the Auto PopupJavadoc Window to False.

Previous - TOC - Next

Page 19 of 58

Page 20: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 20/58

Compiling Java Programs

Using NetBeans IDE 3.6Previous - TOC - Next

Feedback

Basic compilation is simple. You select the file or folder you wantto compile and choose the appropriate Build or Compilecommand. The IDE then compiles the files using the compilationtype you have specified for them. The NetBeans IDE also gives

you tools to deal with more complex project compilation, such as JavaMakeTM for dependencymanagement and advanced compilation options for cross-compiling for different SDK versions.

In this section you will learn about the following:

  Compiling files - the behavior of the Compile and Build commands and viewing output from the

compiler.  Working with compiler types - which one to use, creating custom compiler types, setting the

output target directory.  Cross-compiling between Java platforms - specifying the compiler executable or libraries used

in compilation.  Using JavaMake to Manage Class Dependencies - managing complex dependencies between

Java classes.

Compiling Files

To compile a file or directory, select it in the Filesystems window and choose one of the following from themain window:

  Build > Compile (F9) to compile only those files that are new or have changed since the lastcompile. The up-to-date check is done by comparing timestamps between the source (.java) andproducts (.class) of the compile. This command does not compile the files in subfolders.

  Build > Compile All (Shift+F9) to compile only those files that are new or have changed since thelast compile, including the files in subfolders.

  Build > Build (F11) to build all the selected files from source regardless of their up-to-date status.

This command deletes the sourcename.class files in the folder and compiles the source files. Thiscommand does not remove .class files or compile source files in subfolders.

  Build > Build All (Shift+F11) to build all files from source within the selected folder and itssubfolders .

Any compilation errors and output are displayed in the Output Window. In the Output Window you can:

  Click any error to jump to the location in the source file where the error occurred.  Copy the output to the clipboard by right-clicking in the window and choosing Copy.  Redirect the output to a file by right-clicking in the window and choosing Start Redirection of This

View to File. The output is written to the output directory in your IDE's user directory. You can alsochoose a specific directory to redirect the output to under Output Window settings in the Optionswindow.

Working with Compiler Types

Now that we've seen how compilation is initiated, let's look at how the NetBeans IDE defines the rules forhow compilation is carried out. Compiler types are the IDE's main tool for specifying compilation options.To view and configure compiler types, go to the Options window and expand Building > Compiler Types.

Page 20 of 58

Page 21: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 21/58

Internal Compilation compiles files within the same virtual machine as the IDE using the javac compiler ofthe IDE's default SDK. External Compilation spawns a new VM for compilation. While Internal Compilation

is faster, External Compilation offers you greater configuration options.

All other compiler types shipped with the IDE are basically copies of External Compilation that have beenconfigured for different compiler executables. Additional IDE modules may insert their own compiler types,such as the RMI Stub Compiler from the RMI module.

Specifying the Compiler Type for Files and Projects

You can specify which compiler type is used for compilationat two levels:

  The project-wide default compiler type. Open the

Options window, select Editing > Java Sources, andset the Default Compiler property.

  The compiler type for an individual file. Right-click thefile in the Filesystems window, choose Properties, andset the Compiler property.

Creating Custom Compiler Types

Page 21 of 58

Page 22: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 22/58

Each compiler type contains properties that affect how the compiler generates code, such as whether togenerate debugging information and which libraries to use. You can configure compiler types in the Optionswindow under Building > Compiler Types.

Remember that when you change a compiler type's property, that property is changed for all files that usethat compiler type. If you need to set different options for only some files in your project, you should make

a copy of the compiler type with the desired configuration changes, then set the appropriate files to usethis new compiler type.

You can create a new compiler type with default settings by right-clicking the Compiler Types node in theOptions window and choosing from the New menu. To copy an existing compiler type with all of itssettings, right-click the compiler type and choose Copy. Then right-click the Compiler Types node andchoose Paste > Copy.

Note: You can also change compiler options from any Java source file node's property sheet. Just right-click any Java source file node in the Filesystems window, choose Properties, and click the ellipsis (...) inthe Compiler property. Remember, though, that the properties you change in the Compiler dialog box areapplied to all files that use this compiler type.

Setting the Target Directory for .class Files

By default, the IDE generates your compiled .class files to the samedirectory as the Java source files you are compiling. If you want to keepyour .class files in a separate directory, first mount the target directory inthe IDE. Because the compiler generates classes into subfolders of theclass package, you only need to direct the output to the root of thefilesystem.

For example, in the figure on the right Digits.java is in the package com.

mycompany. If you redirect the compiler output to the build directory, thecompiler automatically generates the com and mycompany directories to

house Digits.class.

Once you have mounted the output directory, select the compiler type'snode in the Options window. The Target property for the node contains acombo box with all mounted filesystems in your project. Select the output directory in the combo box.

For more information on mounting complex project structures, see Advanced Project Setup.

Cross-Compiling Between Java Platforms

By default, the IDE compiles sources against the JDK on which it is running. You may, however, want tocompile an application to optimize it for a specific version of the Java platform. In this case, you will want

to compile the sources against a specific Java platform's system libraries and possibly using a specificcompiler version.

For example, you might be developing an application that is designed to run on JDK 1.3 while running theIDE on JDK 1.4. In this case, want to configure the compiler type for your source files to use the JDK 1.3compiler. To do so, select the compiler type type used by your source files (for example, ExternalCompilation) in the Options window. Then click the ellipsis button in the External Compiler property. TheExternal Compiler dialog box, shown below, opens.

Page 22 of 58

Page 23: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 23/58

This dialog defines how the IDE makes calls to the compiler executable. The Process field points to theexecutor that is used. In this case, the Process field is using the {jdk.home}variable to point to yourcomputer's default SDK. The Arguments field uses variables to insert the various compilation options thatare defined for the compiler type, such as Debug or Optimize.

To switch this compiler type to use a different Java platform's compiler executable, click the ellipsis buttonand browse to the executable, or type the absolute path to the executable in the field. Also, since you arenot using the JDK 1.4 compiler, make sure to uncheck the Enable JDK 1.4 Source property.

However, you might need to compile an application against an older JDK version without using the olderJDK's compiler. For example, you might need to compile applets against JDK 1.1, but not want to use theJDK 1.1 compiler because of performance reasons. In this case, set the compiler type's Boot Class Pathproperty to the desired Java platform libraries. Again, make sure the Enable JDK 1.4 Source property is

unchecked.

Using JavaMake to Manage Class Dependencies

When you compile Java classes, the compiler performs a basic dependency analysis on the classes you arecompiling. The compiler looks for classes that the class being compiled is dependent on, checks if they areup-to-date as described above, and compiles any classes that are not up-to-date.

For simple projects this is often enough. For code with complex dependency relationships, however, thenormal Java dependency checking mechanism isn't enough. For examples of what kinds of dependencyrelationships are missed by javac, see http://www.experimentalstuff.com/Technologies/

Page 23 of 58

Page 24: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 24/58

JavaMake/index.html.

NetBeans IDE solves this problem by integrating JavaMake, a tool that provides more extensivedependency management between Java classes. You can enable JavaMake for all of your project's Javaclasses by selecting Editing > Java Sources in the Options window and checking the Use JavaMakeproperty.

The first time you compile a project with JavaMake, the IDE examines all of the classes in a project'smounted filesystems and records the dependency information in a project database. The IDE only recordsdependency information for filesystems which have compilation enabled. The IDE uses this informationduring compilation to perform a complete check for any dependent classes that need compilation.

When JavaMake is enabled, the Compile and Build commands behave differently than when using normalcompilation. The behavior of the commands is as follows:

  Compile/Build. Only compiles or builds the selected files without checking the status of dependentclasses.

  Compile All/Build All. Compiles the selected file and checks all dependent classes. If any dependentclasses are not up-to-date, the IDE compiles them. These commands effectively build or compile theentire project, regardless of which class they are run on

Previous - TOC - Next

Page 24 of 58

Page 25: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 25/58

Debugging Java Programs

Using NetBeans IDEPrevious - TOC - Next

Example Code: 

  arrayFill.java

  sampleBean.java

Feedback

NetBean's debugging features

expand on the capabilitiesprovided by the JPDA debugger.You can visually step throughsource code and monitor the stateof watches, variables, strings, andother elements of your code'sexecution.

In this section you will learn about:

  Basic debugging - Starting a debugging session, using theDebugger windows, and stepping through your code.

  Working with breakpoints - Adding and removing a breakpoint,

different types of breakpoints, setting breakpoint conditions, andcustomizing the output of a breakpoint.

  Setting watches - Adding a watch or fixed watch to an object.

Basic Debugging

In this section, we will use a simple example to demonstrate how to start adebugging session, step through your code manually, and monitor variablesand method calls in the Debugging workspace. We will leave more advancedfunctions like setting breakpoints and watches for the following sections.

Our example for this section is the arrayFill program. This program is

very simple. It creates an array of sampleBeans, each one of which has twoproperties, firstName and lastName. It then assigns values to the

properties of each bean and prints out the values.

The first thing you want to do is run the program to see if it throws anyexceptions. Open arrayFill.java and press F6 to execute it. The followingoutput should appear in the Output window:

java.lang.NullPointerException  at arrayFill.loadNames(arrayFill.java:27)  at arrayFill.main(arrayFill.java:34)Exception in thread "main"

Page 25 of 58

Page 26: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 26/58

Starting a Debugging Session

When you start a debugging session in the IDE, the IDE compiles the filesthat you are debugging, runs them in debug mode, and displays debuggeroutput in the Debugger windows. To start a debugging session, select thefile that you want to debug and choose one of the following commands fromthe Debug menu:

  Start > Run in Debugger (Alt-F5). Runs the program until the firstbreakpoint is encountered.

  Step Into (F7). Starts running the program and stops at the firstexecutable statement.

  Run to Cursor (F4). Starts a debugging session, runs the programto the cursor location in the Source Editor, and pauses the program.

Since you did not setany breakpoints in theexample program, justselect arrayFill in the

Filesystems window andpress F7. The IDE opensthe file in the Source

Editor, displays theOutput window andDebugger windows, andstops just inside themain method.

Debugger Windows

Let's take a minute to look at the Debugger windows. The Debuggerwindows automatically open whenever you start a debugging session and

close when you finish the session. By default, the IDE opens three Debuggerwindows: the Local Variables window, Threads window, and Call Stackwindow.

You can open other Debugger windows by choosing from the Window >Debugger menu. When you open a Debugger window during a debuggingsession, it closes automatically when you finish the session. If you open a

Page 26 of 58

Page 27: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 27/58

Debugger window when no debugging session is open, it stays open untilyou close it manually. You can arrange Debugger windows by draggingthem to the desired location.

The following table lists the Debugger windows.

Name Shortcut Description

LocalVariables

Ctrl-Alt-1 Lists the local variables that are within thecurrent call.

Watches Ctrl-Alt-2 Lists all variables and expressions that youelected to watch while debugging yourprogram.

Call Stack Ctrl-Alt-3 Lists the sequence of calls made duringexecution of the current thread.

Classes Ctrl-Alt-4 Displays the hierarchy of all classes that havebeen loaded by the process being debugged.

Breakpoints Ctrl-Alt-5 Lists the breakpoints in the current project.

Sessions Ctrl-Alt-6 Lists the debugging sessions currentlyrunning in the IDE.

Threads Ctrl-Alt-7 Lists the thread groups in the currentsession.

All in One Ctrl-Alt-8 Provides session, threads, calls, and localvariables in a single view.

Stepping Through Your Code

You can use the following commands in the Debug menu to control howyour code is executed in the debugger:

  Step Over (F8). Executes one source line. If the source line containsa call, executes the entire routine without stepping through theindividual instructions.

  Step Into (F7). Executes one source line. If the source line containsa call, stops just before executing the first statement of the routine.

  Step Out (Alt-Shift-F7). Executes one source line. If the source line

Page 27 of 58

Page 28: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 28/58

is part of a routine, executes the remaining lines of the routine andreturns control to the caller of the routine.

  Pause. Pauses program execution.  Continue (Ctrl-F5). Continues program execution. The program will

stop at the next breakpoint.  Run to Cursor (F4). Runs the current session to the cursor location

in the Source Editor and pauses the program.

In our example, use theF7 key to step through thecode one line at a time.The first time you pressF7, you are presentedwith a dialog saying that

the IDE couldn't find java.lang.ClassLoader.

loadClassInternal in the mounted filesystems. If you want to be able to

step through methods in the JDK as well, mount the JDK sources in theFilesystems window. Otherwise, use the Step Out option in this dialog tohave the debugger execute the process without trying to open the file in thedebugger.

The NullPointerException occurred in the loadNames call, so when youstep to that call, watch the value of the names array in the Local Variables

view. Each of the beans have a value of null. You can continue steppingthrough the loadNames method - the names beans are null throughout.

The problem here is that while the line

  sampleBean[] myNames=new sampleBean[fnames.length];

initiates the array that holds the beans, it does not initiate the beansthemselves. The individual beans have to be initiated in the loadNames method by adding the following code in line 28:

  names[i]=new sampleBean();

Working With Breakpoints

Most programs are far too big to examine one line at a time. More likely,

Page 28 of 58

Page 29: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 29/58

you set a breakpoint at the location where you think a problem is occurringand then run the program to that location. You can also set morespecialized breakpoints, such as conditional breakpoints that only stopexecution if the specified condition is true or breakpoints for certain threads

or methods.

In this section, we will use the arrayFill program from the last example,

so you will have to recreate the bug by commenting out the code you addedabove.

Setting a Breakpoint

If you just want to set a

simple line breakpoint,you can click the leftmargin of the desired line.A line breakpoint icon ( )appears in the margin.You can remove the linebreakpoint by clicking itagain.

For more complex breakpoints, use the New Breakpoint (Ctrl-Shift-F8)

command in the Debug menu. The New Breakpoint dialog box lets youchoose the type of breakpoint you want to create and set breakpoint optionssuch as conditions for breaking or the information that the breakpoint printsto the Output window.

Setting Conditions for a Breakpoint

Conditional breakpoints only stop execution if a specified boolean expressionis true. If you want to set a conditional breakpoint, open the NewBreakpoint dialog box and enter an expression in the Condition field.

For example, open arrayFill.java, set the insertion point in the

loadNames method call in the main method, and press Ctrl-Shift-F8. In the

dialog box, enter myNames=null in the Condition field and click OK. The

conditional breakpoint icon ( ) appears in the margin before the methodcall. Then press Alt-F5 to start debugging the program. The executionshould break at the loadNames method call.

Page 29 of 58

Page 30: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 30/58

Customizing the Output for a Breakpoint

In the New Breakpoint dialog box, you can also specify what information isprinted when a breakpoint is reached. Enter any message in the Print Textfield at the bottom of the dialog box. You can use variables to refer tocertain types of information you want displayed.

Breakpoint Types

The following table lists the different breakpoint types that are available.

Type Description

Line You can break execution when the line is reached, or whenelements in the line match certain conditions.

Page 30 of 58

Page 31: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 31/58

Method When you set a breakpoint on a method name, programexecution stops every time the method is executed.

Exception You have several options for setting a breakpoint on anexception. You can break whenever a specific exception iscaught, whenever a specific exception is not handled in thesource code, or whenever any exception is encounteredregardless of whether the program handles the error or not.

Variable You can stop execution of your program whenever a variablein a specific class and field is accessed (for example, themethod was called with the variable as an argument) ormodified.

Thread You can break program execution whenever a thread starts,stops, or both.

Class When you set a breakpoint on a class, you can stop thedebugger when the class is loaded into the virtual machine,unloaded from the virtual machine, or both.

Setting Watches

A watch enables you to track the changes in the value of a variable orexpression during program execution. To set a watch, select the variable or

expression you want to set a watch on in the Source Editor, then right-clickand choose New Watch (Ctrl-Shit-F7).

You can also create fixed watches in the Watches view. While a normalwatch describes the content of a variable, a fixed watch describes the objectthat is currently assigned to the variable. To create a fixed watch, right-clickany item in the Local Variables or Watches view and choose Create FixedWatch.

Previous - TOC - Next

Page 31 of 58

Page 32: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 32/58

Packaging and Deploying Your Applications

Using NetBeans IDE 3.6Previous - TOC - Next

Example Code: 

  NetBeans example code 

(ZIP)

Feedback

The standard tool used for packaging and deploying Java applications is the JavaArchive (JAR) file format. JAR files are packaged with the ZIP file format. You can useJAR files for simple compression and archiving of your application class files, or you canspecify more advanced options like signing and verifying your JAR files or making themrunnable. The IDE provides several features that help you to easily create and workwith JAR files.

This section covers the following topics:

  Creating a JAR File - Using JAR recipes to specify JAR file contents and

properties, creating a manifest, creating and mounting the JAR file.  Modifying a JAR File - Adding and removing files to an existing JAR file, making changes to the manifest, and setting

custom file filters.  Executing a JAR File - Specifying the main method in the manifest and executing your application.

Creating a JAR File

To create a JAR file in the IDE, you first create a JAR recipe that specifies the contents and properties of the JAR file. You thencreate the JAR file itself by running the Compile command on the JAR recipe file. In this example we will create a JAR file usingthe example sources that are automatically mounted in the IDE when you first start the IDE. If you have lost or deleted theexample sources, you can download them using the link above.

Creating a JAR Recipe

To create a JAR recipe, choose File > New from the Main window. In the wizard, expand the JAR Archives node, choose JARRecipe, and click Next. In the second page of the wizard, specify the name and location of the JAR file you are going to produce.

The third page of the wizard is where things start getting interesting. This is where you specify the contents of the JAR file.Select any directory or file from the panel in the left of the wizard and use the Add button to schedule it for inclusion in the panelon the right. The panel on the left shows all of your mounted filesystems. At this point you can click Finish to create the JARrecipe, or click Next to specify more detailed options.

Page 32 of 58

Page 33: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 33/58

The fourth page of the wizard lets you set special options for the JAR file contents. The most important part of this page is theTarget Directory column, which shows the directory structure of the JAR file's contents. For Java sources, the directory structuremust correctly match the Java package structure of the Java classes. If the filesystem from which you added the contents wascorrectly mounted at the Java package root, this should automatically be configured correctly. For example, the target directoryfor our examples.colorpicker.ColorPicker class is correctly set at examples/colorpicker.

Finally, the fifth page of the wizard lets you generate the manifest file for the JAR file. The JAR manifest file contains metainformation for handling the files contained in the JAR file, such as the location of the main method or signing information. For

more information about the JAR manifest file, click here.

In the JAR Manifest page of the wizard, you can generate basic manifest information automatically, enter information by hand, oruse an existing file as the manifest file. For now, let's just enter the basic manifest information by clicking the Generate button.Then click Finish to create the JAR Recipe.

Page 33 of 58

Page 34: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 34/58

The JAR recipe node appears in the Filesystems window, as shown in thefigure on the right. The JAR recipe node includes a subnode for the JAR fileit creates and a Contents subnode listing all of the JAR recipe contents. Youcan use the property sheet to modify the contents and properties of the JARrecipe, such as the compression level and file filter used to produce the JARfile. To open the property sheet, right-click the JAR contents node andchoose Properties.

Compiling and Creating the JAR File

Once you have created a JAR recipe, you can compile its contents and create the JAR file by right-clicking the JAR recipe andchoosing Compile. The contents of the JAR file are compiled using whatever compiler types and settings you assigned to them inthe IDE. See Compiling Java Programs for more information on compilation settings.

Mounting and Checking the JAR File

If you want to check your JAR file to make sure that the directory structure and manifest file are correct, you can mount the JARfile in the Filesystems window. To mount the file, right-click the JAR recipe node or the JAR file node under it and choose MountJAR. You can then expand the JAR file to view its contents and execute any executable classes it contains. Mounting a JAR alsoadds it to the project's classpath.

Modifying a JAR File

Once you have created a JAR recipe, you can modify all aspects of the JAR file that it produces. Your main tool for modifying aJAR recipe is its property sheet. You can open the property sheet by right-clicking the JAR recipe node and choosing Properties.Whenever you modify the JAR recipe, you can update its corresponding JAR file with your changes by recompiling the JAR recipe.

Note: If you make any changes to the JAR recipe and recompile the JAR file, these changes are not reflected in the mounted JARfile. You have to unmount the JAR file and mount it again to view the changes.

Adding Files to a JAR Recipe

You can add files to a JAR recipe using the Contents property in the JAR recipe's property sheet. The Contents property editorlets you add files and directories to the JAR recipe like you do in the JAR Recipe wizard. The Chosen Content pane on the rightalso contains the Target Directory and Target Name info, so you can check that the JAR file's directory structure is correct.

Page 34 of 58

Page 35: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 35/58

In our case, we want to add the entire colorpicker directory to the JAR recipe, since the ColorPicker application will not workwithout the other classes in the directory. To do so, select the directory and click Add. Then click OK and recompile the JARrecipe to update the JAR file.

Modifying the Manifest File

To modify the manifest file, open the property sheet for the JAR recipe node and click the ellipsis button for the Manifestproperty. The Manifest property editor is basically the same as the Manifest page in the JAR Recipe wizard. You can enter themanifest information by hand, generate the basic information using the Generate button, or use an existing manifest file usingthe Load From File button.

Setting the JAR Content Filter 

Use a JAR recipe's File Filter property to specify which types of files should be included in your JAR file. When you create a JARfile, you usually want to include just the compiled .class files and any other resource files located in your source directory, such

as resource bundles or XML documents. The default JAR filter does this for you by excluding all .java, .jar, and .form files fromyour JAR file.

Regular Expression Description

\.html$ Include all HTML files

\.java$ Include all Java files

(\.html$)|(\.java$) Include all HTML and Java files

(Key)|(\.gif$)Include all GIF files and any files withKey in their name

In the File Filter property editor, you can also set the filterusing a POSIX-style regular expression. The RegularExpression field checks your expression's syntax and displaysany invalid expressions in red text. The custom filter is storedin the JAR recipe file, so you can use or edit the filter if youlater modify the JAR.

The table on the right provides some examples of regularexpressions you can write. For a guide to regular expressionsyntax, click here.

Executing a JAR File

In order to execute a JAR file, you must first specify the JAR file's main class in the manifest. If the sources in your JAR filedepend on sources located in other JAR files, the manifest must also contain the classpath to those JAR files. It is not enough tohave the JAR files mounted in the IDE, since the IDE classpath is ignored when running a JAR file.

To make the example JAR file runnable, open the Manifest property editor for its JAR recipe and add the following line:

Main-Class: examples/colorpicker/ColorPicker

Then compile the JAR recipe to produce the new JAR file. You can then run the JAR file by right-clicking the JAR recipe node andchoosing Execute. The ColorPicker application should open in a new window.

Page 35 of 58

Page 36: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 36/58

Previous - TOC - Next

Page 36 of 58

Page 37: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 37/58

Using Javadoc

Using NetBeans IDE 3.6Previous - TOC - Next

Example Code: 

  NetBeans example code 

(ZIP)

Feedback

Javadoc is the Java programming language's tool for generating APIdocumentation. Java API documentation describes important elementsof your code, such as methods, parameters, classes, fields, and soforth. You can insert special Javadoc comments into your code so thatthey will be automatically included in the generated documentation.

Describing your code within the code itself rather than in a separatedocument helps to keep your documentation current, since you canregenerate your documentation as you modify it.

In this section, you will learn about the following:

  Integrating Java API documentation into the IDE - Searching for and displaying Javadoc, mounting

and configuring Javadoc filesystems, configuring the IDE's Web browser to display Javadoc files, andintegrating Javadoc with code completion.

  Adding Javadoc comments to your code - Rules and special tags for Javadoc comments, tools for

automatically commenting your code, and correcting errors in comments.  Generating Javadoc documentation - Using the standard Javadoc doclet, initializing generation, and

specifying the output directory for the generated files.

Integrating Java API Documentation into the IDE

The IDE lets you integrate API documentation for the code you are working on into the IDE itself. You can thenquickly bring up the documentation for any classes in your code or even when you're looking for a particularclass or method in the code completion box. The referenced API documentation can be stored in an archive file,regular directory, or on the Internet.

Making Javadoc Documentation Available in the IDE

In order to make Javadoc documentation available in the IDE, you must mount the documentation as a Javadocfilesystem. A Javadoc filesystem is any directory, archive file, or location on the Internet that contains APIdocumentation.

You mount Javadoc filesystems in by choosing Tools > Javadoc Manager from the main window. Use the Addbuttons to add the appropriate type of Javadoc filesystem. You must mount each filesystem at the directorythat contains the Javadoc index, which is located in a document called index.html file or a directory called

index-files. (Sometimes both an index file and an index directory are present). The directory that contains

the Javadoc index is usually called api or apidocs.

For example, if you want to make the NetBeans Execution API documentation available directly from thenetbeans.org portal, click Add HTTP and enter http://www.netbeans.org/download/dev/javadoc/

ExecutionAPI/.

Page 37 of 58

Page 38: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 38/58

For each filesystem, you can specify the following:

  Hidden. Specifies whether this filesystem is visible in the Filesystems window. You should set thisproperty to False if you want to browse through the documentation tree in the Filesystems window.

  Search Engine. Specifies the default Javadoc search engine. The Japanese version of the search enginelets you to search internationalized Javadoc documentation.

  Root Offset. If your Javadoc documentation is inside a JAR or zip file, the Javadoc index is sometimesburied in the file's hierarchy. Since you can only mount the JAR or zip file as a whole, you have to set theRoot Offset for these filesystems to the directory that contains the Javadoc index. (For HTTP and localfilesystems, you just mount the filesystem directly at the directory that contains the Javadoc index.)

Searching and Displaying Javadoc Documentation

The easiest way to search for Javadoc documentation for any element of Java code is to select any occurrenceof the element in the Source Editor and press Shift-F1. Doing so opens the Javadoc Index Search in a SourceEditor tab. The Javadoc Index Search tab displays all matching entries in your mounted Javadoc filesystems.Select any search result to view the Javadoc in the bottom panel of the dialog box, or double-click a searchresult to open it in the IDE's external browser.

Page 38 of 58

Page 39: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 39/58

If you prefer to browse through your Javadoc filesystem hierarchy, choose the Javadoc filesystem from theView > Documentation Indices menu. The filesystem's index page is opened in your external web browser.

Configuring the External Browser to Display Javadoc Files

Javadoc files are displayed in the IDE's designated web browser. To set the IDE's designated web browser,choose Tools > Setup Wizard and choose a browser from the Web Browsers combo box. The Setup Wizard listsall of the web browsers installed on your system.

Page 39 of 58

Page 40: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 40/58

If you select a web browser and it does not open correctly, it is possible that the IDE does not have the correctlocation for the browser executable. You can configure the web browser by opening the Options window,expanding IDE Configuration > Servers and External Tool Settings > Web Browsers and selecting the webbrowser. Open the property editor for the Browser Executable property, then click the ellipsis button for theProcess field to locate your browser executable. Then click OK to exit the dialog box.

If your Web browser uses a proxy to access the Internet from behind a firewall, you must also configure thebrowser to bypass the proxy for local files. If this option is not set, you could get a 404 File Not Found error

when you try to display Javadoc files that reside on your local machine.

Adding Javadoc Comments to Your Code

Javadoc comments are special comments (marked by a /**, as opposed to a /* for regular comments) thatdescribe your code. When you generate Javadoc documentation for a source file, all of the Javadoc commentsin the file are automatically included in the documentation. You can put special tags describing elements of yourcode in Javadoc comments and format your comments with XHTML tags.

The IDE provides an Auto Comment tool that analyzes your code for any elements that have incomplete orincorrect documentation and lets you enter the documentation right in the tool. To see how the Auto Commenttool works, let's use it on one of the example files that comes with the IDE. In the IDE's default project, go tothe examples/colorpicker directory and double-click the ColorPreview Java file node to open the file in the

Source Editor.

The ColorPreview class is a simple bean that sets the background color for a visual component to various

Page 40 of 58

Page 41: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 41/58

colors. The code is already completely documented, so to see how the Auto Comment tool works let's first putsome errors in the documentation. In the comment above the addPropertyChangeListener method, remove

one of the stars (*) to change it from a Javadoc comment to a regular comment.

Now right-click anywhere inside the Source Editor and choose Tools > Auto Comment. The Auto Comment toolshows all of the methods in the file that should be commented in the top left of the tool. You can use thebuttons above this field to choose which methods are processed by the tool.

As you can see, all of the methods in the file have the green "correct Javadoc" icon except foraddPropertyChangeListener, which has a red "missing Javadoc" icon. Select addPropertyChangeListener to

see what problem the tool found with the method's comment. Use the View Source button to jump to the line inthe Source Editor where the method first appears and the Refresh button to rescan the file for incorrectcomments. You can add Javadoc comment text and tags in the right side of the tab.

Generating Javadoc Documentation

Once you have entered Javadoc comments into your code, you can generate the HTML Javadoc files for yoursource files. The Java language uses a program called a doclet to generate and format the API documentationfiles. Although there are numerous doclets that produce documentation in a wide variety of formats, thestandard doclet used by the IDE generates HTML documentation pages.

To generate documentation, right-click any file or folder and choose Tools > Generate Javadoc. By default, thedoclet generates the documentation files to the javadoc directory in your user directory. The doclet generates

the Javadoc index files (including frame and non-frame versions, package lists, help pages explaining how thedocumentation is organized, and so forth) into the javadoc directory. Individual files describing each class are

generated into subdirectories that match the directory structure in your source tree. For example, if you run the

Page 41 of 58

Page 42: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 42/58

Generate Javadoc command on the sampledir filesystem, the javadoc directory contains the Javadoc index

for the filesystem and a directory called examples with all of the individual documentation files.

Specifying an Output Directory for Javadoc Files

You can specify any mounted filesystem as the output directory for generated Javadoc files. For example, if youwant to create a docs directory to house API documentation for sources in the sampledir filesystem, create the

docs directory somewhere on your system and mount it in the IDE. Then go to the Options window, select CodeDocumentation > Doclets > Standard Doclet, and choose the docs directory in the Destination property.

Previous - TOC - Next

Page 42 of 58

Page 43: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 43/58

Team Development With CVS

Using NetBeans IDE 3.6Previous - TOC - Next

Feedback

Version control software (VCS) programs track the changes to a set of filesand manage how users access and change those files. A VCS is anessential tool for any team of developers that works on a common codebase. It lets you roll back any unwanted changes, avoid conflicts when twodevelopers alter the same file, and establish different development branches on the same codeline.

NetBeans IDE integrates VCS functionality right into the IDE itself, letting you view versioning status and run VCScommands on files in the Filesystems window. The IDE uses VCS profiles to pass commands and arguments to theVCS executable on your machine. Profiles for Concurrent Versioning System (CVS), Visual Safe Source (VSS) andPolytron Version Control System (PVCS) are included in the IDE, and you can download experimental profiles forother VCS programs from the netbeans.org website. The IDE also includes a built-in CVS executable that you canuse without having CVS installed on your computer.

In this section, we will cover the basics of using CVS in the IDE. Although command usage differs between VCSapplications, many of the concepts discussed here are common to all VCS applications.

This section covers:

  Checking Out Sources - Mounting CVS filesystems, selecting which sources to check out, and running CVS

commands.  Configuring a CVS Filesystem - Configuring CVS filesystems and changing the display of file status

information.  Working With CVS Files - Generating diffs and patches, applying patches, and resolving merge conflicts.

  Making Safe Commits - Finding all modified files in your working directory, checking for mistakes,

committing your changes.

Checking Out Sources

Like all source files, you have to mount version controlled sources in the Filesystems window to be able to work withthem. You mount version controlled sources in a VCS filesystem. A VCS filesystem is just like a regular IDEfilesystem, except that it is directly linked to the VCS repository so you can use it to call VCS commands right in theFilesystems window. You can mount a source directory that is already under version control, or mount an empty

directory and check out source files from the CVS repository.

To illustrate how to check out sources in the IDE, let's check out the Beans module from the NetBeans CVSrepository. We will use the anoncvs guest account, so you do not have to worry about registering with netbeans.org

to complete this example.

Mounting a CVS Filesystem

To get started, choose Versioning > Mount Version Control from the main window. In the wizard, select CVS in theVersion Control System Profile combo box.

Page 43 of 58

Page 44: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 44/58

Now you can start filling in the CVS repository information. First, you need to create a directory to house thesources. Click the Browse button in the Working Directory field and create a directory called beans somewhere on

your system. Then fill in the following CVS server information:

  CVS Server Type - pserver   CVS Server Name - cvs.netbeans.org

  CVS Server User Name - the anonymous login name, anoncvs

  CVS Repository - the location of the sources on the repository server, /cvs

  Use Built-In CVS Client - sets which CVS client the IDE uses

Before you finish mounting the CVS filesystem, you have to log in to the server. Click the Login button withoutentering a password. . (No password is necessary for the anoncvs account.) If the command succeeds, the text

beneath the Password field changes to You are already logged in. If the command fails, check your connectionto the Internet and your firewall settings.

Page 44 of 58

Page 45: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 45/58

Note: To use CVS, you must be able to access the Internet on the CVS port (2401 by default).

Click Finish to close the wizard and mount the filesystem. A new CVS filesystem node appears in the Filesystemswindow.

Now that you have mounted thefilesystem, you can get the sourcesfrom the repository. Right-click thefilesystem node and select the CVSsubmenu. This submenu containsCVS commands that you can runon your files. Hold down the Ctrlkey and choose Checkout from theCVS menu.

The CVS Checkout dialog box letsyou set advanced options for theCVS Checkout command. The "." inthe Module(s) field indicates thatyou want to check out the entireCVS repository. Since we only want

to check out the Beans module,enter beans in this field and clickOK. Alternatively, you can click theSelect button to view a list of allmodules in the repository and thenselect from the list.

Once you run the command, theVCS Output window opens listingthe CVS command status and theCVS output. You can kill thecommand by clicking the Stopbutton. When the commandfinishes, you can expand thefilesystem and begin working withthe files.

Specifying Advanced Command Options

The IDE's CVS support lets you set all of the command options that are available on the command line. To see acommand dialog in which you can specify advanced command options, hold down the Ctrl key when choosing acommand from the CVS commands menu. You can also configure a VCS filesystem to always display the advancedoptions dialog of CVS commands. Right-click the filesystem's node in the Filesystems window and choose Properties,

then set the filesystem's Advanced Command Options property to True.

Configuring a CVS Filesystem

Once you have checked out your files, you can usually start working with them immediately. You may, however,need to further configure the filesystem to correctly build the Java classpath or display VCS status information. Thetwo main tools for configuring a CVS filesystem are the VCS filesystem customizer, in which you can change theserver and user information that you entered when mounting the filesystem, and the filesystem's property sheet.Right-click the filesystem and choose Customize to view the filesystem's customizer, or choose Properties to viewthe filesystem's property sheet.

Page 45 of 58

Page 46: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 46/58

Setting the Relative Mount Point

Like all Java filesystems in the IDE, CVS filesystems must be mounted at the directory that contains the defaultpackage. In order for all your VCS commands to function correctly, however, the filesystem must be mounted at theworking directory root. You can resolve this problem by mounting the filesystem at the working directory root, thensetting the relative mount point at the default package root.

For example, the default package for the sources in the Beans filesystem is in the src directory. To set the relativemount point, right-click the filesystem node and choose Customize. Click the Select button in the Relative MountPoint field, expand beans, and select src. Then click OK to apply your changes.

If you want to mount more than one directory as a default package root, hold down the Ctrl key, select all of therelative mount points, and click OK. Each relative mount point is mounted as its own filesystem.

Shortening and Hiding File Status

Expand the Beans filesystem to take a look at howNetBeans IDE displays CVS status information. Thename of each file is followed by the file's status, itsrevision number, and if you are working on a branchalso the branch tag name. If you double-click a file to

open it in the Source Editor, you will notice that theCVS status information is also printed on the file'sSource Editor tab.

This status information can actually be problematic,because it makes the Source Editor tabs take up a lotof room. One solution is to set Shorten File Statuses toTrue in the filesystem's property sheet . This optionsaves some space, but not very much.

As you can see, the IDE also displays a badge for eachfile that expresses its CVS status. The badges and theirmeanings are shown in the table below.

Badge Description

Locally modified

Locally removed

Merge conflict

Needs checkout

Up-to-date

For the most part, you probably just want to know whether a file is up-to-date or not.You can therefore hide all file status information and just use the badges. If you need tosee more versioning information, like the file's version number or sticky tag information,you can always run the CVS Status command on the file.

To hide all status information, open the filesystem's property sheet and click the ellipsisin the Annotation Pattern property. The Annotation Pattern property editor shows a nodefor each type of CVS status information, plus subnodes that govern how the informationis displayed. Simply delete each node (except the Variable:filename node, of course)

and click Apply Changes. If you find that you miss the status info, you can alwaysdisplay it again by opening this dialog box and clicking Restore Defaults.

Working With CVS Files

One of the main advantages of CVS is that it lets you see how your files evolve as you and members of yourdevelopment team make changes to them. NetBeans IDE expands on this functionality by making it easier to viewchanges to files and resolve conflicts between file revisions. It also makes it easier to prepare your checkins andcheck for mistakes before you commit.

Using the Graphical Diff Tool

When diff version-controlled files on the command line, the diff command compares two file revisions and printsout the differences between the two revisions along with the line numbers where they occurred. Although manycommand-line users are adept at reading long diff print outs, new users (and even some command-line veterans)often find this format confusing.

Page 46 of 58

Page 47: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 47/58

NetBeans IDE uses a graphical diff viewer to display both file revisions side-by-side with the differences highlighted.The repository version is shown in the left pane, and your working file is shown in the right pane. You can use thebuttons in the top left-hand corner of the viewer to navigate through the revision differences.

To run a graphical diff on a file, right-click it in the Filesystems window and choose CVS > Diff Graphical. If you runthe command without any advanced options specified, it compares your working directory version with the headrevision in the repository. If you want to specify which revisions to diff by tag name or date, hold down the Ctrl keywhile choosing the command and enter the information in the advanced command dialog.

Unlike the Diff Textual command, you cannot run the Diff Graphical command on a directory. You can, however,select several files in the Filesystems window and run the Diff Graphical command on them. The diff for each fileappears in its own Source Editor tab. As we will see in the Making Safe Commits section, you can also use the

Search Results window as a powerful tool to find and diff all Locally Modified files in a filesystem.

Creating and Applying Patches

A patch file lets you take a snapshot of the changes between two revisions and send them to another developerwithout checking in the changes or even requiring the other developers to have a CVS connection to the repository.Patch files are often used when a development team wants to evaluate a proposed change before checking it intothe repository.

To create a patch, right-click the directory or file you want to create the patch from and choose CVS > Diff Textual.Click OK without specifying any options if you want to diff your working directory against the current head revisionin the repository, or enter any additional options like specific tags or dates.

Page 47 of 58

Page 48: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 48/58

The patch is displayed in the VCS Output window. Right-click inside the VCS Output window and choose Save toFile, then specify a location and name for the file.

To apply a patch file, right-click the exact file or directory from which the patch was created and choose Tools >Apply Patch. Then browse to the location of the patch file and click OK. If you want to undo the changes made bythe patch, you can delete the modified files and then run the Update command to get a clean version from therepository.

Resolving Merge Conflicts Graphically

When you update a locally modified file, CVS merges changes from the repository with the changes you have madeto your local file. If someone else on your development team has committed changes to the same lines that youhave changed in your working directory, a merge conflict occurs.

CVS marks merge conflicts by bracketing the offending lines with error markers (<<<<<< and >>>>>>>). In thefollowing example, the changes to the field name have generated the merge error. The first line of the error showswhat you have in the working directory, and the second line shows what is in the repository.

<<<<<<< ColorPreview.java  private int yellow;  =======  private int orange;  >>>>>>> 1.2

Normally, you would open the file in a text editor, delete the error markers and the version you do not want tokeep, and commit the file. (You do not necessarily have to choose one of the two versions - you could writesomething completely new.) As long as the error markers are present in the file, CVS will not let you check it intothe repository.

The IDE provides a Merge Conflicts Resolver that makes resolving merge conflicts easier. To open the tool, right-click any file whose status is Merge Conflict and choose Resolve Conflicts. The Merge Conflicts Resolver looks verysimilar to the Graphical Diff tool - it displays the repository revision on the right, working revision on the left, andthe final version in the bottom.

Page 48 of 58

Page 49: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 49/58

Use the Accept buttons to choose which of the two versions you want to accept. You can use the Accept & Nextbuttons to resolve a conflict and jump to the next conflict. You cannot write into the bottom panel of the MergeConflicts Resolver, so if you want to write something new rather than accepting either of the two versions, close thedialog and resolve the conflict manually in the Source Editor.

Making Safe Commits

CVS lets you roll back most changes to the repository, so for the most part you do not have to worry about yourcommits doing permanent damage to your project. Still, introducing code that breaks your project's build process orintroduces critical bugs is embarrassing and time-consuming to fix. This can often happen not because your codecontained bugs, but because you forgot to check something in or checked something in that you did not mean to.

You can make sure your commits are safe by following these simple steps:

1. Update your sources. Always make sure that the sources in your working directory match what is presentlyin the repository. To update sources, right-click any CVS filesystem node or folder node and choose CVS >Update.

2. Search by VCS status. Right-click the CVS filesystem node and choose Refresh Recursively to make sure allfile status information is current. Then right-click the CVS filesystem node and choose Find. Click the Statustab, select Up-To-Date, and select the Match Only Files That Do Not Meet the Selected Criteria check box.Click OK to list all files that are not up-to-date in the Search Results window. You can then run all your CVScommands from the Search Results window.

3. Remove any unwanted files from the search results. Make sure the Search Results window onlycontains those files you want to commit. You can remove any file from the Search Results window by right-

Page 49 of 58

Page 50: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 50/58

Page 51: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 51/58

Configuring the IDE

Using NetBeans IDE 3.6Previous - TOC 

Feedback

One of the main strengths of NetBeans IDE is its versatile configurability. You cancustomize your working environment to fit your needs and personal developmentstyle. Having all of these options can, however, make it difficult to find the exactsetting you are looking for.

In this section you will learn about the following:

  Setting IDE default settings - Using the Options window and startup switches, setting general settings for Java

source files, and dealing with unknown file types.  Enabling and disabling functionality - Turning modules on and off and downloading new modules from the Update

Center.  Boosting NetBeans performance - Getting better performance using startup parameters, disabling modules, and

manually initializing garbage collection.

Setting IDE Default Settings

The main tool for configuring default settings in the IDE is the Options window. You can open the Options window bychoosing Tools > Options.

IDE settings are grouped under Options window nodes in the left panel of the window. Select any node to set its propertiesin the right panel of the window. As with regular property sheets, many properties in the Options window contain specialproperty editors. You can tell that a property editor is available for a property if the property contains an ellipsis button, as inthe Error Expression property in the figure above.

Most changes you make to IDE settings are applied to the open project. Only settings that you are not likely to vary from

project to project, like indentation settings for the Source Editor or proxy information, are applied to all projects. The icontells you that a particular settings node is defined at the project level.

You can apply project-level settings to all projects by clicking the << at the top of the options window, clicking the node'scell in the User column, and choosing Define Here. To revert a node's settings to the IDE's factory defaults, choose Revert toDefault in the node's Default column.

Page 51 of 58

Page 52: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 52/58

Configuring IDE Startup Switches

Another tool for configuring the IDE is Java startup switches. You can add startup switches to NetBeans IDE on the commandline or by entering them in a special file called ide.cfg, which is located in the same directory as the launcher itself($NB_HOME/bin). You can enter IDE-specific startup switches and pass arguments directly to the JVM in which the IDE runs.

For example, to set the -Xmx (maximum heap size) for the JVM in which NetBeans IDE runs, either add the line -J-Xmx64m to

your ide.cfg file or launch the IDE by typing

./runide.sh -J-Xmx64m

on UNIX systems, or, on Windows systems

runide.exe -J-Xmx64m

The ide.cfg file can have the various JVM switches separated either by spaces or on separate lines. Note that the Sun JVMdoes not start when passed switches that it does not understand. When this error occurs, the JVM returns a messagepointing out the switch that caused the problem, as with the following example:

java -fooUnrecognized option: -foo

Could not create the Java virtual machine.

The following table lists the startup switches that are available.

Startup Switch Description

-h

--help

Print descriptions of common startup parameters.

--jdkhome jdk_home_dir  Use the specified version of the Java 2 SDK instead of thedefault SDK. By default on Windows systems, the loaderlooks into the Windows registry and uses the latest SDKavailable.

--cp:a additional_classpath

--cp additional_classpath 

Append the specified classpath to the IDE's classpath.

This option is generally recommended only for addingcustom look and feel implementation JARs, which youmay instead add to NetBeans IDE lib/ext/ directory.

-J jvm_flag   Pass the specified flag directly to the JVM.

--laf UI_class_name  Use a given class as the IDE's look and feel.

--fontsize size  Use a given size in points as the basic font size for theIDE user interface.

--locale language[:country[:variant]]  Use the specified locale.

--userdir userdir   Explicitly specify the userdir, which is the location inwhich user settings are stored. If this option is not usedon a UNIX system, the location is ${HOME}/.

netbeans/3.6. On Microsoft Windows systems, thedefault is .netbeans\3.6 beneath your default Windowsprofile area (e.g. c:\Documents and Settings\yourlogin).

--open file  Mounts the directory containing the specified file in theFilesystems window and opens the file in the SourceEditor.

--open file:line number   Mounts the directory containing the specified file in theFilesystems window and opens the file in the SourceEditor at the specified line.

Configuring General Java Settings

Page 52 of 58

Page 53: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 53/58

The first thing you should do to configure the IDE is make sure it is using the correct Java Standard Development Kit (JDK)version. The JDK in which the IDE runs is important because it is automatically used as the platform against which all of yoursources are compiled and executed. (You can, of course, configure the IDE for cross-compiling on a different Java platform

than the one the IDE is using.)

To see which JDK your IDE is running on, choose Help > About and click the Detail tab. The JDK's locations is listed underJava Home. By default, the IDE uses the JDK that is specified in your system's registry as the latest one. If you only haveone version of the JDK installed on your computer, this is not a problem. If you have multiple JDK versions installed, it can

be a good idea to explicitly specify which one the IDE should use. You can do so by using the --jdkhome  JDK directory  switch (for example, --jdkhome c:\j2sdk1.4.0\) on the command line or in your ide.cfg file.

Note that if you are developing code for use on JDK version 1.4, you must have the Enable JDK 1.4 Source property set toTrue on both the Java Sources node and your compiler type in the Options window. You must also have the Enable Assertsproperty set to True on your Default Debugger and External Execution. These options allow features introduced in JDKversion 1.4, such as assertions, to be properly handled by the JVM.

Another important tool in defining Java settings is the JavaSources node in the Options window. The Java Sources node,which is located under the Editing node, contains generalsettings for how the IDE handles Java source files. You can usethe Java Sources node to do any of the following:

  Set the default service types (Default Compiler, DefaultDebugger, and Default Executor) for Java source files.For each of these properties, you can click the ellipsisbutton to configure the service types themselves.

  Enable JavaMake for Java compilation (Use JavaMake).  Define whether Java source files are parsed every time

you open containing folder in the Filesystem window(Prescan Sources) and how quickly they are parsed afteryou make changes to them (Automatic Parsing Delay).If you set Prescan Sources to False, the IDE only parsessource files when you run an action on them, like openingthem or expanding their Filesystem window node. Thismakes browsing through large directory trees faster, butthe icons for the node do not show whether the filecontains a main method or errors until the file is parsed.

Working With Unknown File Types

The IDE recognizes the standard file extensions for most types of files. For example, it knows that files with the extensions .htm, .html, and .shtml should all be treated as HTML files. Many file types, like XML, can have nonstandard file extensionsthat the IDE does not recognize.

When the IDE runs across a file whose extension it does not understand, it displays the file as a generic file icon in theFilesystem window. You can right-click the file and choose Treat as Text to open it in the Source Editor as a text file.

If you want to treat all files with a certain file extension as a certain type of file, go to the Options window and expand IDEConfiguration > System > Object Types. The Object Types node contains all of the file types that the IDE is currentlyconfigured to work with. You can use the Extensions and MIME Types property to specify which file extensions should betreated as a given type of file.

For example, JavaHelpTM map files are XML documents that have a .jhm extension. You can treat all JavaHelp map files asXML documents by adding .jhm to the list of Extensions and MIME Types for the XML Object object type.

Enabling and Disabling IDE Functionality

NetBeans IDE is a fully modular IDE, meaning that its functionality is provided by modules that plug into the core NetBeansinfrastructure. If you do not use the functionality provided by certain modules, you can turn those modules off. Turning off

Page 53 of 58

Page 54: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 54/58

unused modules helps improve your IDE's startup time and performance. You can also add functionality to your IDE bydownloading new modules from the Update Center.

Disabling Modules

The Setup wizard is the most convenient tool for enabling and disabling modules. Disabling a module only causes the IDE toignore the module. The module is not deleted and it can be enabled again at any time.

To open the Setup wizard, choose Tools > Setup Wizard, then click Next to go to the Module Installation page of the wizard.

The Module Installation page groups related modules into module groups. For example, the Distributed Application Supportgroup contains all of the modules that deal with distributed application development. You can disable all modules in a modulegroup by unchecking the checkbox in its Enabled column, or expand the module group node to disable individual modules.When only certain modules in a module group are disabled, the Enabled column for the group displays

[boolean]. When you

are finished, click Finish to activate your changes.

Certain modules depend on other modules to function properly. Disabling or enabling one of these modules may require youto also disable or enable the modules upon which it depends. If this is the case, the IDE displays a dialog that tells you whichmodules will also be disabled or enabled and asks for your confirmation.

Installing New Modules from the Update Center 

You can add functionality to your IDE by downloading new modules from the NetBeans Update Center. To connect to theUpdate Center, choose Tools > Update Center from the main window. In the Update Center wizard, select the UpdateCenters that you want to connect to. Make sure that your proxy information is properly configured and that you can connectto the Internet. You can edit your proxy configuration using the Proxy Configuration button on the wizard page. Click Next

Page 54 of 58

Page 55: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 55/58

when you are ready to proceed.

The second page of the wizard shows you all of the modules that are available on the Update Centers. The wizard onlydisplays modules that are not already installed in your IDE or newer versions of modules that are already installed. Newerversions of modules that you already have are marked with an upward arrow, like the Ant 1.5.1 Documentation module inthe figure below. Select any module to see detailed information about the module, including a description, the versionnumber of the module on the Update Center, and the version number of the module already installed on your system.

To schedule a module for installation, select it in the window on the left and click the right arrow button. To install an entiregroup of modules, select the module group node and click the double right arrow. When you are ready to proceed, click theNext button to view the modules' certificates and install the modules.

Boosting NetBeans Performance

You can monitor your IDE's performance with the Memory toolbar. To view the Memory toolbar, right-click anywhere in thetoolbar area and select the Memory checkbox. The toolbar has a slide that shows you how much of the IDE's memory iscurrently being used and how close it is to automatically performing garbage collection. You can manually initiate garbagecollection by clicking the Memory toolbar button.

You can boost NetBeans performance in the following ways:

  Disabling prescanning for Java source files. When prescanning for Java source files is enabled, the source files inany directory are parsed the first time you open the directory that contains them in the Filesystem window.Prescanning source files lets the IDE show whether the file contains a main method or compilation errors in the file'snode. It also makes expanding through source directories slower. You can disable source prescanning by going to theJava Sources node in the Options window and setting the Prescan Sources property to False. The file is then parsedonly when you open the file in the Source Editor or expand it in the Filesystem window.

  Switching off unused modules. As noted above in Disabling Modules, switching off unused modules can

significantly decrease the IDE's startup time. For example, if you do not program distributed applications or JavaGUIs, you can turn off the JNDI and Form Editor modules. NetBeans IDE's memory footprint while running is alsosmaller the less modules you have installed.

  Adjusting the JVM switches with which you start the IDE. See below.

Tuning JVM Switches for Performance

JVMs offer a variety of standard and non-standard switches that tune memory allocation and garbage collection behavior.Some of these settings can benefit NetBeans IDE's performance.

Note that -X and especially -XX JVM switches are officially "unsupported" because they are often JVM or JVM-vendorspecific. The switches discussed in this section are available for Sun Microsystems J2SE 1.4.1 - users of other JVMimplementations may need to remove these switches in order to run the IDE.

The following settings should produce better-than-factory setting performance on most systems. With the exception ofsetting the "permanent area" size, these switches have been the defaults for the IDE for some time, and should already bepresent in your ide.cfg file.

  -J-Xverify:none - This switch turns off Java bytecode verification, making classloading faster and eliminating theneed for classes to be loaded during startup solely for the purposes of verification. This switch improves startup time,and there is no reason not to use it.

  -J-Xms24m - this setting tells the Java virtual machine to set its initial heap size to 24 megabytes. By telling the JVMhow much memory it should initially allocate for the heap, we save it growing the heap as the IDE consumes morememory.

  -J-Xmx96m - this setting specifies the maximum amount of memory that the the Java virtual machine should use forthe heap. Placing a hard upper limit on this number means that the Java process cannot consume more memory thanphysical RAM available. This limit can be raised on systems with more memory - the 96 megabyte setting helps toensure that the IDE performs tolerably on 128Mb to 256Mb systems. Note: Do not set this value to near or greaterthan the amount of physical RAM in your system or it will cause severe swapping during major collections.  

  -J-XX:PermSize=20m - this is a more exotic JVM switch, but one which also improves startup time. This settingsizes the "permanent area" of memory, where classes are kept. Since we know that all of NetBeans IDE's classes takeup a specific amount of memory, we give the JVM a hint as to how much memory it will need. This setting eliminatesmajor garbage collection events during startup on many systems. Users of SunONE Studio or other IDEs that includemore modules may want to set this number higher.

Listed below are some additional JVM switches which have either anecdotally or measurably impacted NetBeans performanceon some, not all, systems. Your mileage may vary, but they may be worth a try.

Page 55 of 58

Page 56: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 56/58

  -J-XX:CompileThreshold=100 - This switch will make startup time slower, by HotSpot to compile many moremethods down to native code sooner than it otherwise would. The reported result is snappier performance once theIDE is running, since more of the UI code will be compiled rather than interpreted. This value represents the numberof times a method must be called before it will be compiled.

  -J-XX:+UseConcMarkSweepGC -J-XX:+UseParNewGC - Try these switches if you are having problems withintrusive garbage collection pauses. This switch causes the JVM to use different algorithms for major garbagecollection events (also for minor collections, if  run on a multiprocessor workstation), ones which do not "stop theworld" for the entire garbage collection process. If you are using the PermSize switch, you should also add the line -J-

XX:+CMSClassUnloadingEnabled to your ide.cfg file so that class unloading is enabled (it isn't by default when usingthis collector). Note: It is unclear as yet if this collector helps or hurts performance on uniprocessor machines.  

  -J-XX:+UseParallelGC - Some tests have shown that, at least on systems fairly well equipped with memory, thedurations of minor garbage collections is halved when using this collection algorithm, on uniprocessor systems. Notethat this is paradoxical - this collector is designed to work best on multiprocessor systems with gigabyte heaps. Nodata is available on its effect on major garbage collections. Note: this collector is mutually exclusive with -J-XX:

+UseConcMarkSweepGC . . The measurements supporting the use of this algorithm can be found on the performance 

web site.

Previous - TOC 

Page 56 of 58

Page 57: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 57/58

 /*

 * arrayFill.java

 *

 * Created on March 6, 2003, 7:01 PM

 *

 * This nicely demonstrates how to manage array of beans, mainly each array cell has to be initialized separately

 */ 

 /**

 *

 * @author bohemius

 */ 

public class arrayFill {

 

private final static String[] fnames={"Jack", "Bob", "Lao", "Michael"};

  private final static String[] lnames={"Wood", "Goat", "Duck", "Bond"};

 

private static void printNames(sampleBean[] names) {  for (int i=0; i<names.length; i++) {

  System.out.println(names[i].getFirstName()+", "+names[i].getLastName());

  }

  }

 

private static void loadNames(sampleBean[] names) {

  for (int i=0;i<names.length;i++) {

  names[i].setLastName(lnames[i]);

  names[i].setFirstName(fnames[i]);

  }

  }

  public static void main(String[] args) {

  sampleBean[] myNames=new sampleBean[fnames.length];

  loadNames(myNames);

  printNames(myNames);

  }

 

}

Page 57 of 58

Page 58: Manual Oficial Netbeans 3.6

8/20/2019 Manual Oficial Netbeans 3.6

http://slidepdf.com/reader/full/manual-oficial-netbeans-36 58/58

 /*

 * sampleBean.java

 *

 * Created on March 6, 2003, 7:05 PM

 */ 

import java.beans.*;

 /**

 *

 * @author bohemius

 */ 

public class sampleBean extends Object implements java.io.Serializable {

 

private String lastName;

  private String firstName;

 

private PropertyChangeSupport propertySupport;

  /** Creates new sampleBean */ 

  public sampleBean() {

  propertySupport = new PropertyChangeSupport( this );

  }

 

public String getLastName() {

  return lastName;

  }

 

public void setLastName(String value) {

  String oldValue = lastName;

  lastName = value;

  propertySupport.firePropertyChange("Last name", oldValue, lastName);

  } 

public String getFirstName() {

  return firstName;

  }

 

public void setFirstName(String value) {

  String oldValue = firstName;

  firstName = value;

  propertySupport.firePropertyChange("First name", oldValue, firstName);

  }

 

public void addPropertyChangeListener(PropertyChangeListener listener) {

  propertySupport.addPropertyChangeListener(listener);

  } 

public void removePropertyChangeListener(PropertyChangeListener listener) {

  propertySupport.removePropertyChangeListener(listener);

}