I have a project in netbeans in which I have a java scanner which has been generated using jflex. So when I usually build this using a make file I use the -Xlint option, that is
javac -Xlint javaScanner.java
But now when I am creating the jar file using the clean and build option it is showing the following error.
init:
deps-clean:
Updating property file: /home/mridula/testPrjct/sDvait-LCS/build/built-clean.properties
Deleting directory /home/mridula/testPrjct/sDvait-LCS/build
clean:
init:
deps-jar:
Created dir: /home/mridula/testPrjct/sDvait-LCS/build
Updating property file: /home/mridula/testPrjct/sDvait-LCS/build/built-jar.properties
Created dir: /home/mridula/testPrjct/sDvait-LCS/build/classes
Created dir: /home/mridula/testPrjct/sDvait-LCS/build/empty
Created dir: /home/mridula/testPrjct/sDvait-LCS/build/generated-sources/ap-source-output
Compiling 35 source files to /home/mridula/testPrjct/sDvait-LCS/build/classes
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 1 file to /home/mridula/testPrjct/sDvait-LCS/build/classes
compile:
Created dir: /home/mridula/testPrjct/sDvait-LCS/dist
Copying 1 file to /home/mridula/testPrjct/sDvait-LCS/build
Copy libraries to /home/mridula/testPrjct/sDvait-LCS/dist/lib.
Building jar: /home/mridula/testPrjct/sDvait-LCS/dist/sDvait-LCS.jar
To run this application from the command line without Ant, try:
java -jar "/home/mridula/testPrjct/sDvait-LCS/dist/sDvait-LCS.jar"
jar:
BUILD SUCCESSFUL (total time: 2 seconds)
If I could know how the file is being built. I could just add the -Xlint option so that the jar file could be created without a problem.
Netbeans uses ant to build java projects. There is a build.xml file in your project dir that handles this process.
But you have another option:
Right click your project node, choose "Properties" (a dialog box pops up). On the left choose "Compiling" and add your options in the field "Additional compiler options"
It seems the answer doesn't work....
I'm using some apache HttpClient jars, so I put them in my project's lib directory, when Netbeans compiles the project, it copies the lib and generated a project jar into dist directory, but when I run my project with webstart, I need to copy the project jar and lib into tomcat's ROOT dir, I wonder if Netbeans can generate a project jar that includes all the jars in the lib dir, so I don't have to copy the project jar and the lib dir into tomcat's ROOT dir. Can Netbeans do that ?
That's really easy to package every dependent library (*.jar) into one single myProject.jar.
Just follow these steps and you will finally pack every dependent library into single jar. If you are using NetBeans then you can follow exactly or else you need to find your build.xml file in project files.
Follow these steps to edit build.xml
1) Click on Files tab
on the left side of the project panel in NetBeans.
2) Double click on the build.xml
file and add these lines in it just before line
3) Change value
in second line of the code as per your project name which is
//<---Just value not name
4) Save it and right click on build.xml and choose Run Target and then Other Targets and finally click on Package-for-store
5) And here you done. Now you can go and check just like dist
folder there will be a store
folder which will be containing your final complete jar including all of your dependent libraries. Now whenever you want to change / add more libraries or so, just follow step 4.
love you man, worked like a charm, I was struggling in Neatbeans for a SINGLE jar. I was using FAT jar in Eclipse and was missing an alternative in Netbeans. Thanks again
Robert Eckstein describes a solution for this problem. You just need to paste the following code to build.xml
. The libraries are all found automatically.
Here we go:
Go to your build.xml, and add the code right before the closing project tag at the end.
Now change the value of the first propertiy field as commented
Click Clean & Build, and your jar will be in the dist folder
Reference link: https://stackoverflow.com/a/30172829/2761273
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes
Okay, so this is my solution. I too had the problem with my program compiling and running on Netbeans but it failing when I tried java -jar MyJarFile.jar
. Now, I don't fully understand Maven and I think this why was having trouble getting Netbeans 8.0.2 to include my jar file in a library to put them into a jar file. I was thinking about how I used to use jar files with no Maven in Eclipse.
It's Maven that compiles all the dependencies and plugins, not Netbeans. (If you can get Netbeans to do this please tell us how.)
[Solved - for Linux] by opening a terminal.
Then
cd /MyRootDirectoryForMyProject
Next
mvn org.apache.maven.plugins:maven-compiler-plugin:compile
Next
mvn install
This will create jar file in the target directory.
MyJarFile-1.0-jar-with-dependencies.jar
Now
cd target
(You may need to run: chmod +x MyJarFile-1.0-jar-with-dependencies.jar) And finally
java -jar MyJarFile-1.0-jar-with-dependencies.jar
Please see
https://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
This chapter provides an overview of the building features in NetBeans.
This chapter contains the following sections:
About Building Java Projects
Working with Ant
Working with Builds
Building a Java Project
Using a Build Server
Compiling a Single Java File
Building a JAR File
Packaging an Application as a Native Installer
Preparing a JAR File for Deployment Outside the IDE
Using the Output Window
Refactoring Java Projects
Working with Maven in the IDE
Working with Maven Repositories
NetBeans provides both Ant and Maven for building your Java applications. With Ant, if you are using a standard Java project, the IDE generates an Ant build script based on the options you enter in the project's Project Properties dialog box. If you are using a free-form Java project, the IDE uses your existing Ant build script.
With standard Java projects, you can customize the build process by doing any of the following:
Enter basic options, such as classpath settings and JAR filters, in the Project Properties dialog box.
Override IDE-generated Ant targets or create new targets in build.xml
.
By default, the IDE compiles the classes in a standard project when you save them. This compile-on-save feature enables you to run or debug your applications in the IDE without having to wait for the projects to be built. However, the compile-on-save feature does not build your application JAR file. Before delivering your application to users, use the Clean and Build command to generate fresh versions of the project's distributable files.
For standard projects that have a main class specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib
folder when you build the application. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf file. This simplifies running the application outside the IDE. For more information, see Section 8.9, "Preparing a JAR File for Deployment Outside the IDE."
For information on how to customize an Ant build script, see Section 6.2.3.4, "Customizing the IDE-Generated Ant Script."
For information on how to modify a build JAR file, see Section 8.7, "Building a JAR File."
Maven is a framework that provides help with managing the project lifecycle, including building and managing dependencies. Maven projects follow a set of standards that are described with a Project Object Model (POM) file. You build the project using its POM and a set of plugins that are shared by all projects using Maven to ensure consistency between projects.
When you build, the IDE executes the plugin goals, builds the project and adds the project artifacts to the local repository. Maven uses repositories (local or remote) to contain a project's build artifacts and dependencies.
By adhering to convention, Maven frees you from having to explicitly specify every build action, configure the path to source files, and so on as it uses a default setup. Even though Maven is based on convention, you can customize a project by creating a custom configuration where you can map IDE actions to Maven goals enabling you to load the project in the IDE with a specific set of dependencies and trigger specific actions.
For information on using Maven in the IDE, see Section 8.12, "Working with Maven in the IDE."
For information on configuring Maven settings, see Section 8.12.2, "How to Configure Maven Settings."
For more information on Maven repositories, see Section 8.13, "Working with Maven Repositories."
Apache Ant is a Java-based build tool used to standardize and automate build and run environments for development. Ant build scripts are XML files that contain targets, which in turn contain tasks. Ant tasks are executable bits of code that handle the processing instruction for your source code. For example, you use the javac task to compile code, the java task to execute a class, and so forth. You can use Ant's built-in tasks, use tasks written by third parties, or write your own Ant tasks.
For more information about Ant, see http://ant.apache.org
/.
For information on installing Ant documentation, see Section 8.2.9, "How to Install Ant Documentation in the IDE."
The IDE's project system is built directly on top of Ant version 1.9.0. All of the project commands, like Build Project or Run File in Debugger, call targets in the project's Ant script. Therefore, you can build and run your project outside the IDE exactly as it is built and run inside the IDE. For information on mapping Ant targets to debugger commands, see Section 6.2.4.6, "Mapping an Ant Target to an IDE Command."
You do not need to be familiar with Ant to work with the IDE. You can set all the basic compilation and runtime options in your project's Project Properties dialog box and the IDE automatically updates the project's Ant script. If you know how to work with Ant, you can customize a standard project's Ant script or write your own Ant script for your project. For more information on customizing an Ant script, see Section 8.2.8, "Ant Classpaths and Custom Tasks."
Note:
Though the IDE is built directly on top of Ant, the parsers that usually come with Ant are not necessarily bundled with the IDE. If you require parsers not included with the IDE distribution, you can add them to Ant's classpath using the Ant Settings > Additional Classpath property in the Options window.
For more help with the IDE's Ant support, see the NetBeans Ant FAQ at http://wiki.netbeans.org/
.
For information on modifying the classpath for a project, see Section 6.2.3.1, "Managing the Classpath."
In standard projects the IDE generates the build script based on the options you enter in the New Project wizard and the project's Project Properties dialog box. You can set all the basic compilation and runtime options in the project's Project Properties dialog box and the IDE automatically updates your project's Ant script. If you have additional requirements for the build process that cannot be handled in the Project Properties dialog box, you can modify the build script directly.
The main Ant script for a standard project is build.xml
. The IDE calls targets in build.xml
whenever you run IDE commands. This file contains an import statement that imports nbproject/build-impl.xml
, which contains build targets that are generated by the IDE. In build.xml
, you can override any of the targets from nbproject/build-impl.xml
or write new targets. Do not edit nbproject/build-impl.xml
directly, because that file is regenerated based on changes that you make in the Project Properties dialog box.
In addition, the build script uses the nbproject/project.properties
which you can edit manually.
Editing an Ant script is much like editing any other XML file. All of the applicable Source Editor shortcuts are available. Double-click any of the Ant script's subnodes in the Files window to jump to that target's location in the Source Editor.
The IDE provides code completion for all standard Ant tasks. To enter an end tag for any empty beginning tag, type .
With standard projects, you can customize the build process by doing any of the following:
Entering basic options, like classpath settings and JAR filters, in the New Project wizard when you create a project, or afterwards in the Project Properties dialog box.
Editing properties in nbproject/project.properties
. This file stores Ant properties with important information about your project, such as the location of your source and output folders. You can override the properties in this file. Be careful when editing this file. For example, the output folder is deleted every time you clean your project. You should therefore never set the output folder to the same location as your source folder without first configuring the clean target to not delete the output folder.
Customizing existing or creating new Ant targets by doing any of the following:
Add instructions to be processed before or after an Ant target is run. Each of the main targets in nbproject/build-impl.xml
also has a -pre
and -post
target that you can override in build.xml
. For example, to get RMI working with regular projects, type the code from Example 8-1 in build.xml
.
Example 8-1
Change the instructions in an Ant target. Copy the target from nbproject/build-impl.xml
to build.xml
and make any changes to the target.
Create new targets in build.xml
. You can also add the new target to the dependencies of any of the IDE's existing targets. Override the existing target in build.xml and then add the new target to the existing target's depends property. For example, code from Example 8-2 adds the new-target
target to the run target's dependencies.
Example 8-2
You do not need to copy the body of the run target into build.xml
.
The following table lists some common tasks for redefining a JAR file that you may find useful.
To perform this task | Follow these steps |
---|---|
Specify which files are added to a JAR file. | Right-click the project node in the Projects window and choose Properties. Click the Packagingsubnode (under Build) and configure the filter and compression settings using the Exclude from JAR File field. |
Change a JAR file's name and location. | In the Files window, double-click the project's nbproject/project.properties file to open it in the Source Editor. Enter the full path to the JAR file in the dist.jar property. |
Specify the manifest file for a JAR file. | In project.properties , type the name of the manifest file in the manifest.file property. The file name must be specified relative to the project's build.xml file. Note that if you are using the Java Application template, the IDE creates a manifest file for you. |
Disable the generation of a JAR file for a project. | In the Files window, open your project folder and open build.xml . Override the jar target to have no contents and no dependencies. For example, add the following to build.xml : |
The IDE automatically recognizes Ant scripts and displays them as Ant script nodes ( ) rather than as normal XML files. You can right-click Ant scripts in the Projects window, Files window, or Favoriteswindow to access a context menu of commands. You can also expand the Ant script node to see an alphabetical list of subnodes representing the Ant script's targets. Each of these subnodes also has a context menu of commands.
In the Projects, Files, and Favorites windows, an Ant script's subnodes are flagged in the following ways:
Icon | Meaning |
---|---|
Emphasized Ant target. These targets include a description attribute, which is displayed as a tooltip. You define the target's description attribute in the Source Editor. | |
Normal Ant target. A target without a description attribute. |
Double-click any of the Ant script's subnodes to jump to that target's location in the Source Editor. All of the normal XML search tools, selection tools, and keyboard shortcuts are available for editing Ant scripts, and the IDE provides code completion for all standard Ant tasks.
When you create a target that you want to run from the command line, give the target a description attribute. Then, if you forget the names of the targets or what they do, you can run the ant -projecthelp
command from the command line. With this command, Ant lists only those targets that have a description attribute, together with their descriptions. Especially when there are many targets in your Ant build script, emphasizing some and de-emphasizing others can be a useful way to distinguish between those that you use a lot and those that you use less often.
The font style of a subnode's label in the Projects, Files, and Favorites windows indicates the following:
Normal. A target that is defined within the current Ant script.
Italics. A target that is imported from another Ant script.
Greyed out. An internal target that cannot be run directly. Internal targets have names beginning with -
.
Bold. The default target for the script, if there is one. The default target is declared as an attribute of the project, together with other project attributes, such as its name. You define the project's default attribute in the Source Editor.
Targets that are imported from another script but are overridden in the importing script are not listed. Only the overriding target is listed.
8.2.2.1 Writing Custom Ant Tasks
You can use custom Ant tasks to expand on the functionality provided by Ant's built-in tasks. Custom tasks are often used to define properties, create nested elements, or write text directly between tags using the addText
method.
To create a custom Ant task in the IDE:
Right-click the package where you would like to place the task and choose New > Other.
Select the Other category and the Custom Ant Task file type.
Complete the wizard.
When you create the custom Ant task file, the template opens in the Source Editor. The template contains sample code for many of the common operations performed by Ant tasks. After each section of code, the template also shows you how to use the task in an Ant script.
The IDE runs targets in your project's Ant script any time you run commands on your project. You can also manually run a target in any Ant script from the Ant script's node in the Files window or Favorites window.
To run a target in an Ant script:
Right-click the Ant script node and choose the target you want to run from the Run Target submenu.
Targets are sorted alphabetically. Only emphasized targets are listed.
Choose Other Targets to run a target that has not been emphasized with a description attribute. Internal targets are excluded from these lists because they cannot be run independently.
Select the Ant script node to display its targets in the Navigator window. Then right-click the target node and choose Run Target.
The Output window displays compilation errors generated by Ant scripts as normal Java code compilation errors. You can double-click any error message to jump to the location in the source where the error occurred.
Note:
For free-form projects, you need to modify the Ant script to map IDE commands to Ant targets. For more information, see Section 6.2.4.6, "Mapping an Ant Target to an IDE Command."
To stop a running Ant script:
Choose Run > Stop Build/Run from the main menu.
For resources on learning Ant, see http://ant.apache.org/resources.html
.
To install the Ant manual into the IDE help system by using the Plugins Manager:
Choose Tools > Plugins and install the Ant Documentation module.
You can run an Ant script in the IDE's debugger like you would a Java class. Debugging an Ant script is handy when you need to diagnose a problem in the Ant script's execution or examine how the script works.
To debug an Ant script:
Right-click the Ant script node in the Projects window, Files window, or Favorites window and choose any target from the Debug Target menu.
When you start debugging an Ant script, the IDE opens the Debugger windows, goes to the first line of the target, and stops. You can perform all of the following operations:
Use the Step Into (F7), Step Over (F8), Step Out (Ctrl+F7) commands to go through the Ant script one line at a time.
View the values of instantiated properties in the Local Variables window.
Set a watch on a property by choosing Run > New Watch (Ctrl+Shift+F7).
Set a line breakpoint by clicking in the Source Editor's left margin and use the Continue (F5) command to run the Ant script to the line.
Set a conditional breakpoint by choosing Run > New Breakpoint (Ctrl+Shift+F8).
See the hierarchy of nested calls in the Call Stack window.
For information on using the debugger window, see Chapter 10, "Running and Debugging Java Application Projects."
You can create a mini-script that serves as a shortcut to a commonly used target in an Ant script. You can also customize the way the target is run. The shortcut can be saved as a menu item, toolbar button, or keyboard shortcut.
To create a shortcut to a target:
Select the build script node in the Files or Favorites window to display its targets in the Navigation window.
Right-click the target node and choose Create Shortcut.
Specify where you want to place the shortcut and whether you want to customize its Ant code and click Next.
Use the remaining pages of the wizard to assign the shortcut to a toolbar, menu, or keyboard shortcut. The wizard only shows those steps that you selected in Step 3.
To ensure you do not overwrite any existing keyboard shortcuts, you can view existing keyboard shortcuts by choosing Tools > Options and clicking Keymap.
In the Customize Script page, add or change any of the shortcut script's elements, such as tasks or properties. This page only appears if you selected the Customize generated Ant code checkbox in Step 3.
When you have specified all of the necessary information, click Finish. The shortcut is created in the specified locations.
You can use the Options window to configure Ant Settings that effect the behavior of Ant in the IDE.
To configure Ant Settings:
From the main window, choose Tools > Options.
Click the Miscellaneous category and then click the Ant tab.
Modify the properties as desired.
You can set the following properties:
Ant Home. Displays the installation directory of the Ant executable used by the IDE. You can change Ant versions by typing the full path to a new Ant installation directory in this property. You can only switch between versions 1.5.3 and higher of Ant.
The Ant installation directory must contain a lib/
subdirectory which contains the ant.jar
binary. For example, for the standard Ant 1.5.4 release, the Ant installation directory is ant/lib/apache-ant-1.5.4
. If you enter a directory that does not match this structure, the IDE gives you an error.
Save Files. If selected, saves all unsaved files in the IDE before running Ant. It is recommended to leave this property selected because modifications to files in the IDE are not recognized by Ant unless they are first saved to disk.
Verbosity Level. Sets the amount of compilation output. You can set the verbosity lower to suppress informational messages or higher to get more detailed information.
Always Show Output. If selected, fronts the Output window tab if the Ant output requires user input or contains a hyperlink. Output that contains hyperlinks usually denotes an error or warning. If not selected, the IDE always fronts the Output window for all Ant processes.
Reuse Output Tabs. If selected, writes Ant output to a single Output window tab, deleting the output from the previous process. If not selected, opens a new tab for each Ant process.
Properties. Configures custom properties to pass to an Ant script each time you call Ant. Click the ellipsis button to open the property editor. This property is similar to the Ant command-line option, -Dkey=value
.
The default property, ${build.compiler.emacs}
, is available. If you are compiling using Jikes (build.compiler=jikes
), setting this property to true enables Emacs-compatible error messages. It is recommended that you leave this property set to true even if you are not using Jikes, since the IDE prefers Emacs-compatible error messages.
Classpath. Contains binaries and libraries that are added to Ant's classpath. For more information, see Chapter 8, "Ant Classpaths and Custom Tasks."
The IDE comes bundled with Ant version 1.9.0 and uses this installation to run Ant scripts. You can change the version of Ant that the IDE uses by switching the Ant installation directory in Ant Settings. You can only switch between versions 1.5.3 and higher of Ant.
To switch the IDE's Ant version:
Choose Tools > Options from the main window.
Click Miscellaneous in the left panel of the window and expand the Ant node. The Ant Home section displays the current Ant location and version.
Click Manage Ant Home and select a new Ant installation folder.
The Ant installation directory must contain a lib/
subdirectory which contains the ant.jar
binary. If you enter a directory that does not match this structure, the IDE gives you an error.
By default, the IDE ignores your environment's CLASSPATH
variable whenever it runs Ant. For your build script to use custom tasks, you must add the tasks to Ant's classpath in the IDE.
To add custom tasks to Ant's classpath within the IDE:
Configure the Ant classpath settings in the Options window.
Provide an explicit classpath to the tasks in your build script. This is the recommended method.
8.2.8.1 Adding Binaries to Ant's Classpath in the IDE
If you cannot declare a classpath in your build script, or you are using third-party build scripts that you cannot alter, you can add the tasks to Ant's classpath in the IDE. Open the Options window, click Miscellaneous in the left panel of the window, and expand the Ant node. Use the Classpath section to manage the Ant classpath.
Only add items to the Ant classpath that are needed to run custom tasks. Do not use the Classpath settings to manage the compilation or runtime classpath of your project source folders. For information on managing the project classpath, see Chapter 6, "Managing the Classpath." For free-form projects, you must declare the classpath in the project settings as the IDE is unaware of project metadata. For more information, see Chapter 6, "Declaring the Classpath in a Free-Form Project."
8.2.8.2 Build Scripts With an Explicit Classpath
Using an explicit classpath is the recommended method as it ensures that your build scripts are fully portable. You can write your tasks and include instructions to compile them and produce a JAR file in the build file. To use these tasks, include the long form of taskdef
, which includes a classpath. Here is a simple example of such a task:
Example 8-3 Sample of a Task with an Explicit Classpath
The advantage of this method is that no special preparation is needed to begin using the script. The script is entirely self-contained and portable. This method also makes it easier to develop your tasks within the IDE as the script compiles them for you automatically.
To make the your build scripts even more robust, use a property instead of a hard-coded location to specify the classpath to your tasks. You can store the property in the build script itself or in a separate ant.properties
file. You can then change the classpath setting throughout your script by simply changing the value of the specified property.
For information on customizing Ant scripts, see Chapter 6, "Customizing the IDE-Generated Ant Script."
Use the Ant documentation plugin to install the Ant manual in the IDE.
To install the Ant documentation plugin:
Choose Tools > Plugins from the main window.
Select the Available Plugins tab and locate the Ant documentation plugin.
Select the Install checkbox for the Ant documentation plugin and click Install.
Follow the wizard instructions to complete the installation of the plugin.
If you receive the Unable to Connect to the Update Center Server
error message, click OK in the dialog box to close it. Click the Proxy Settings button in the Settings tab of the Plugin manager and set make sure the proxy settings are correct. Click OK and try to connect to the update center again.
The official release of the Ant documentation plugin does not always coincide with the release of the IDE. If you do not see the Ant documentation plugin on the NetBeans Update Center, it may be posted on the NetBeans Beta Update Center.
Before building a project, set the compilation classpath (for details, see Section 6.2.3.1, "Managing the Classpath." After the project is built, fix any build errors that occurred. Build errors are displayed in the IDE's Output window. Once all errors in the code have been corrected, clean the build
and dist
directories by deleting their contents.
You can examine the build output by viewing compiled classes in the project's build
directory and the Javadoc files and built libraries, such as JAR and WAR files, in the project's dist
directory from the Files window.
When you build a project, the IDE calls the corresponding target in the project's Ant build script. The IDE compiles the source files and generates the packaged build output, such as a JAR file or WAR file. You can build a project and all of its required projects, or build any project individually.
You do not need to build the project or compile individual classes to run the project in the IDE. By default, the IDE automatically compiles classes when you save them. These incrementally compiled files are stored in a cache in your user directory and are copied to your project's build folder when you run or debug your project. This incremental compilation can save you a lot of time when you are editing and testing your project. However, you need to build the project to generate distributable files for the project, such as JAR files.
By default, the Build Project command is not enabled since most of that command's functions are handled by the incremental compilation. However, you can use the Clean and Build command to create a fresh build. When you clean and build a project, all previous build outputs are deleted and new versions of the build outputs are created.
To build a project and its required projects:
Select the project that you want to build in the Projects window.
Choose Run > Clean and Build Project (Shift+F11).
Alternatively, right-click the project's node in the Projects window and choose Clean and Build.
The IDE displays the Ant output and any compilation errors in the Output window. Double-click any error to go to the location in the source code where the error occurred.
Note:
If you are building a project often, you can set it as the main project by right-clicking on it in the Projects window and choosing Set as Main Project or by choosing Run > Set Main Project from the main menu and selecting the project in the sub-menu. After you set a project as the main project, the keyboard shortcuts for Run (F6), Build (F11) and Clean and Build (Shift+F11) apply to the main project regardless of which project is selected in the Projects window. Keyboard shortcuts for Debug and Profile also apply to the main project.To stop building a project:
Choose Run > Stop Build/Run from the main menu.
For standard projects that have a main class specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib
folder when you build the project. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf
file. This simplifies running the application outside the IDE. For more information, see Section 8.9, "Preparing a JAR File for Deployment Outside the IDE."
To turn off incremental compilation for a project:
Right-click the project's node and choose Properties.
In the Project Properties dialog box, select the Compiling node and clear the Compile On Save checkbox.
You can compile individual files as well entire project files. For information on compiling individual files, see Section 8.6, "Compiling a Single Java File."
If you need to modify the main class or specify runtime arguments, see Section 10.6, "Setting the Main Class and Runtime Arguments."
The IDE supports creating and starting build jobs using the Hudson build server. Hudson is an open-source server that you can use to build your applications. You can use the Hudson server as part of your continuous integration (CI) process for automated building, verification and testing.
For more information about setting up and using a Hudson build server, see the following documents: http://hudson-ci.org
and http://wiki.hudson-ci.org/display/HUDSON/Meet+Hudson
.
The Jenkins build server also works with the IDE, though this is not as well tested.
To add a Hudson instance:
Right-click the Hudson Builders node in the Services window and choose Add Hudson Instance.
Type the name for the instance to be displayed under the Hudson Builders node.
Specify the server URL, the auto-refresh setting.
Click Add.
After you add a Hudson instance, a node for the instance is added below the Hudson Builders node. You can expand the node to view the status of builds on that instance.
You can specify the application that you want the server to build by creating a new build. When you create the build, you specify the repository containing the sources for the application. A node for the build is added under the node of the target Hudson instance in the Services window. To view additional details about the status of builds, right-click the node for the build and choose Open in Browser.
To set up a new build job:
Choose Team > Create Build Job from the main menu.
Alternatively, in the Services window, right-click the Hudson instance you want to use and choose New Build.
Select the build server instance from the dropdown list.
Specify the name for the build job.
Select the project from the dropdown list.
The build server will use the sources in the project's repository.
Click Create.
After you supply the details for the build, you can start the build process on the server by right-clicking the build that you want to start and choosing Start Job. When a job is building, the node for the job is displayed as running. You can expand the node for the job to view past builds and build artifacts.
Note:
To create builds and start jobs you must have access to a Hudson server.
By default, you do not need to manually compile the files to run your application in the IDE. Files in a standard Java project are compiled automatically when you save the files.
If you have turned off the Compile on Save
feature for a project, you can compile files by building the project or by compiling individual files.
To compile an individual file:
Select the file in the Projects window, Files window, or in the Source Editor and choose Run > Compile File (F9).
If you are using a free-form project, you need an Ant target for this command. The IDE offers to generate a target the first time you choose the command. In the generated target, specify the directory where to put the compiled class. You can do so by specifying a value for the build.classes.dir
property in the generated target. For example, you might add the following line to the line above the
entry:
Alternatively, you can replace the value of the provided build.classes.dir
or rewrite the target entirely.
For information on managing the classpath, see Section 6.2.3.1, "Managing the Classpath."
In standard project, the IDE builds a JAR file from your project sources every time you run the Build command or the Clean and Build command. The JAR file is generated to the dist
directory of your project folder.
For standard projects where the main class is specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib
folder when you build the project. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf
file. This simplifies running the application outside the IDE. For more information, see Section 8.9, "Preparing a JAR File for Deployment Outside the IDE."
When you create a JAR file or a WAR file, 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 filter does this for you by excluding all .java
, .nbattrs
, and .form
files from your output file.
In addition to the default expressions, you can create additional filters using regular expressions to control the output files.
Regular Expression | Description |
---|---|
\.html$ |
Exclude all HTML files |
\.java$ |
Exclude all Java files |
(\.html$)|(\.java$) |
Exclude all HTML and Java files |
(Key)|(\.gif$) |
Exclude all GIF files and any files with Key in their name |
To specify which files are added to the JAR file:
Right-click the project node in the Projects window and choose Properties.
Select the Packaging node in the dialog's left pane.
Specify the files to exclude and any additional settings in the right pane.
To disable generation of a JAR file for a project:
In the Files window, open your project folder and open build.xml
.
Override the jar target to have no contents and no dependencies. For example, add the following to build.xml
:
Alternatively, if you deselect the Build JAR after Compiling option in the Packaging category of the Properties window the Java compiler will produce only.class
files, without building JAR files.
Note:
In free-form projects, JAR file creation is controlled by your Ant script.
See Section 6.2.3.3, "Editing IDE-Generated Ant Scripts" for a description of standard project Ant scripts and properties files. For information on customizing an Ant build script, see Section 6.2.3.4, "Customizing the IDE-Generated Ant Script."
NetBeans IDE supports native packaging for standard Java SE and JavaFX projects. A native package is a wrapper for your project that turns the project into a self-contained, platform-specific installation package. The package contains all the artifacts (source code, Javadoc, Java Runtime and/or JavaFX runtime, a native application launcher, and so on) needed to install and run the application.
Native packaging does not affect the deployment model of a Java SE or a JavaFX project. It enables your project to be packaged with the Java runtime to produce an installer that is common for the operating system you are working in.
Some of the benefits to using native packaging are:
Negates runtime version conflicts since the specific JRE is included in the bundle
Allows for easy deployment of the application using enterprise deployment tools
Can be distributed as a .zip
file or packaged as a platform-specific installer
Before opting for native packaging, however, be aware of the following considerations:
Users might have to go through several steps to download and install the package
Due to the inclusion of the Java runtime (JavaFX runtime for JavaFX applications), the size of the application is significantly larger than a standard packaged application
Application formats are platform-specific (to create a bundle for different operating systems, you must build your project on each platform)
No autoupdate support exists for bundled applications
The following types of packages can be built for the following platforms:
Windows
bundle image
EXE installer (requires Inno Setup 5 or later)
MSI installer (requires WiX 3.0 or later)
MAC OS X:
bundle image
DMG installer
Linux:
bundle image
rpm installer (requires rpmbuild
)
Note that native packaging might require external tools. For instance, if you want to package a Java application to distribute to a non-Windows environment, you need the appbundler
tool, which is not included in JDK7update 6.
Deployment of a Java SE applet (or application) intended to be launched from a web browser and deployment of a JavaFX application are similar in that when a Java SE applet or a JavaFX application are built, both a Java Network Launching Protocol (JNLP) file and a sample html version of the applet are generated. The WebStart engine reads the JNLP file and executes the applet accordingly. The html file defines how the applet is embedded in the web page.
For web page deployment, Java SE and JavaFX applications require the following packaging tools:
bin/javafxpackager
(command-line utility to produce Java SE or JavaFX packages)
lib/ant-javafx.jar
(set of Ant tasks to produce Java SE or JavaFX packages)
These packaging tools are available with JDK version 7 update 6 and later.
For more information on deploying a Java Web Start Application, see Deploying a Java Web Start Application at http://docs.oracle.com/javase/tutorial/deployment/deploymentInDepth/createWebStartLaunchButtonFunction.html
.
For information on using JavaFX packaging tools, see Deploying JavaFX Applications: http://docs.oracle.com/javafx/2/deployment/jfxpub-deployment.htm
.
For information on creating native packaging of a Java SE project in NetBeans, see Packaging a Distributable JavaApp at http://wiki.netbeans.org/PackagingADistributableJavaApp.
For more information on native packaging, see the Native packaging for JavaFX page at the following URL:
https://blogs.oracle.com/talkingjavadeployment/entry/native_packaging_for_javafx
To enable native packaging actions in the project context menu:
Right-click the project node in the Projects window and select Properties from the context menu.
In the Project Properties dialog, choose the Deployment category.
Select the Enable Native Packaging Actions option.
Click OK.
A Package as command is added to the project's context menu. When you are ready to package your application, right-click the project, choose Package as, and select one of the packaging types:
All Artifacts - Creates a package that contains only the project artifacts
All Installers - Creates a package that contains the application image and all applicable installers
Image Only - Creates a package that contains the application image only
EXE Installer - (Windows only) Creates a package as an executable.exe
installer
MSI Installer - (Windows only) Creates a package as an executable.msi
installer
Note:
Contents of the package types is dependent on the platform on which the IDE is running.
When you select a packaging type, a subdirectory is created under the project's dist
directory where the package is stored.
Be aware that the packaging process can take some time to complete and, depending on the tools you are using, progress might not be indicated.
Note that the contents of the submenu are dependent on the operating system you are running on. For example, if running on Linux, an RPM installer is available instead of EXE or MSI. If running on MAC OS, a DMG installer is available.
Whenever you build a standard Java project for which a main class is specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib
folder. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf file. This simplifies running the application outside the IDE.
Though the IDE copies the necessary files to the dist/lib
directory automatically, the following special cases should be kept in mind:
If two JAR files on the project classpath have the same name, only the first JAR file is copied to the lib folder.
If you added a folder of classes or resources to the classpath (as opposed to a JAR file or project), none of the classpath elements are copied to the dist
folder.
If a library on the project's classpath also has a Class-Path element specified in its manifest, the content of the Class-Path element must be on the project's runtime path.
Once you have distributed the archive of your application, the application can be run outside of the IDE from the command line.
To run an application JAR file from the command line:
Navigate to the project's dist
folder.
Type the following:
java -jar.jar
When you run the jar command, the JAR tool uses the JAR manifest to determine the application entry point and the paths to the dependent binaries that are specified in the manifest.mf
file.
The Output window is a multi-tabbed window that displays messages from the IDE. This window is displayed automatically when you encounter compilation errors, debug your program, generate Javadoc documentation, and so on. You can also open this window by choosing Window > Output (Ctrl+4).
One function of the Output window is to notify you of errors found while compiling your program. The error message is displayed in blue underlined text and is linked to the line in the source code that caused the error. The Output window also provides links to errors found when running Ant build scripts and when checking and validating XML documents. For information on validating XML documents, see Section 18.2.5, "How to Validate an XML Document."
If the file that contains the error is open, the Source Editor jumps to the line containing each error as you move the insertion point into the error in the Source Editor. You can also use the F12 and Shift+F12 keyboard shortcuts to move to the next and previous error in the file.
Every action that is run by an Ant script, such as compiling, running, and debugging files, sends its output to the same Output window tab. If you need to save some output, you can copy and paste it to a separate file.
To set Ant to print the command output for each new target to a new Output window tab:
Choose Tools > Options.
Click Miscellaneous in the left panel of the window, expand the Ant node, and select the checkbox in the Reuse Output Tabs property.
When you run a program that requires user input, a new tab appears in the Output window. This tab includes a cursor. You can enter information in the Output window as you would on a command line.
Refactoring is the use of small transformations to restructure code without changing any program behavior. Just as you factor an expression to make it easier to understand or modify, you refactor code to make it easier to read, simpler to understand, and faster to update. And just as a refactored expression must produce the same result, the refactored program must be functionally equivalent with the original source.
Some common motivations for refactoring code include:
Making the code easier to change or easier to add a new feature.
Reducing complexity for better understanding.
Removing unnecessary repetition.
Enabling use of the code for other needs or more general needs.
Improving the performance of your code.
The IDE's refactoring features simplify code restructuring by evaluating the changes that you want to make, showing you the parts of your application that are affected, and making all necessary changes to your code. For example, if you use the Rename operation to change a class name, the IDE finds every usage of that name in your code and offers to change each occurrence of that name for you.
For information on how to refactor an Enterprise Bean, see Section 8.11.22, "How to Refactor an Enterprise Bean."
You can undo any changes that you made using the commands in the Refactor menu. When you undo a refactoring, the IDE rolls back all the changes in all the files that were affected by the refactoring.
To undo a refactoring command:
Go to the Refactor menu in the main menu bar.
Choose Undo.
The IDE rolls back all the changes in all the files that were affected by the refactoring.
If any of the affected files have been modified since the refactoring took place, the Refactoring Undo is not available.
Use the Find Usages command to determine everywhere a class, method, or field is used in your project's source code.
To find where a class, interface, method, or field is used in your project:
In the Projects window or the Source Editor window, right-click the code element and choose Find Usages (Alt+F7).
In the Find Usages dialog box, select options for the scope of the search:
Classes and interfaces
Methods
Fields
Click Find.
The Usages window displays the file name and the line of code for each usage found in that file.
To jump to a specific occurrence of the code element:
Double-click a file name in the Usages window to open the file.
Double-click a line of code to open the file and to position the cursor on that line of code.
8.11.2.1 Classes and Interfaces
For classes and interfaces, the Find Usages command displays all the code lines that:
Use the type, such as creating a new instance, importing, extending, implementing, casting, or throwing.
Use the type's members and static variables
After you choose the Find Usages command on a class or interface, the Find Usages dialog box might give you additional options:
Find All Subtypes checkbox. If selected, only usages of subtypes of the class are displayed.
Find Direct Subtypes Only checkbox. If selected, only usages of direct subtypes are displayed. Subtypes of those subtypes are ignored.
8.11.2.2 Methods
For methods, the Find Usages command displays the code lines that:
Call the method
Override the method
After you choose the Find Usages command on a method, the Find Usages dialog box might give you additional options:
Include overloaded methods checkbox. If selected, any occurrences of overloaded methods are displayed.
Search from Base Class checkbox. If selected, the output shows every usage of that base method. This option only appears if the method that you are finding usages for overrides another method.
8.11.2.3 Fields
For fields, the Find Usages command displays the code lines that:
Set the field to a value
Get the value of a field
8.11.2.4 Additional Find Mechanisms
Other IDE tools that enable you to search for all the places where specific text is used in a project include:
Finding and Replacing Text. Searches for all the places where specific text is used in a source file that is open in the Java Editor. Choose Edit > Find to open the Find dialog box, or choose Edit> Replace to open the Replace dialog box. These commands finds all matching strings, regardless of whether the string is a Java element.
Find in Projects. As with the Find command, the Find in Projects command searches for matching strings, regardless of whether the string is a class name. Choose Edit > Find in Projects to open the Find in Projects dialog box and then type the string of text that you are looking for.
Note:
To find where a method is declared in a source file, you can either double-click the method in the Projects window or Navigator window. If the method is declared in a different source file, right-click the method and choose Go To > Declaration from the context menu.
Use the refactoring Rename command to rename a class or interface. When you rename a class or interface through refactoring, all instances of that class or interface are renamed throughout the project. If you do not want to enact a global change, you can simply select the desired class or interface and edit its name.
To rename a class or interface and update references to it throughout your project:
In the Projects window or the Source Editor window, right-click the class or interface and choose Refactor > Rename from the contextual menu.
In the Rename dialog box, type the new name of the class or interface.
Click Next.
In the Refactoring window, review the lines of code that are affected by the change and clear the checkbox of any code that you do not want changed.
Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. Clean a build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
To rename the class or interface without refactoring:
In the Projects window, rename the class's node inline.
You can rename a class this way by selecting the node of the class and then pressing F2 to make the name editable.
In the Rename dialog box, select the Rename Without Refactoring checkbox.
Click Next.
If you need to back out a refactoring change, see Section 8.11.1, "How to Undo Refactoring Changes."
Use the refactoring Rename command to rename a field or method. As with renaming a class or interface, the scope of a renaming operation is the full scope of the element in the project. Field and method usages are replaced everywhere they appear in the project. Parameters and variables are renamed only in the lexical scope of their definitions. Other elements with the same name are not modified.
To rename a field or method and update references to it throughout your project:
In the Source Editor, right-click the field or method and choose Refactor > Rename from the context menu
In the Rename dialog box, type the new name of the field or method.
(Optional) Click Preview. In the Refactoring window, at the bottom of the Source Editor, review the lines of code that are affected by the change and clear the checkbox of any code that you do not want changed.
Click Do Refactoring to apply the selected changes.
For quick in-place renaming, place the cursor in the item that you want to rename, and press Ctrl+R. Type the new name. Press Escape to finish renaming.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
For information on how to undo refactoring, see Section 8.11.1, "How to Undo Refactoring Changes."
Use the refactoring Move command to move a class to another package. All references to the class are updated the next time you build the project.
To move a class to another package and to change the code that references that class:
In the Projects window or the Source Editor window, right-click the class and choose Refactor > Move from the context menu.
In the Move Class dialog box, select the package from the To Package drop-down list or type the fully qualified package name, such as com.myCom.myPkg
.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
You can also initiate the moving of a class by dragging a class's node in the Projects window to another package's node or by cutting and pasting a class's node.
Always perform a clean build after completing any refactoring commands. Clean a build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
To move a class without doing refactoring:
In the Projects window, manually move the class to another package.
You can cut and paste the class or drag and drop it into another package.
In the Move Class dialog box, select the Move Without Refactoring checkbox.
Click Next.
You can also use the Move command to move the methods and fields of a selected class to another package.
To move the members of a class:
In the Projects window or the Source Editor window, right-click the method and choose Refactor > Move from the context menu.
In the Move Members dialog box, select the package from the drop-down list or type the fully qualified package name, such as com.myCom.myPkg
.
Enter the class name or select the target class from the drop-down list.
Select the members you want to move.
Select the visibility level.
Select whether to keep the Javadoc as it is or update it.
Check the option if you want to keep the original method signatures in the source class and let them call the new methods in the target class.
Check the option if you want the original methods in the source class to be deprecated.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Use the Move Inner to Outer Level command to do move an inner class one level up in hierarchy. For example, if the selected class is directly nested in a top-level class, a new top-level class is created. If the selected class is nested in an inner class, the selected class is moved to the level of the inner class in which it was nested.
To use the Move Inner to Outer Level operation:
In the Source Editor, place the insertion point in the inner class that you want to convert.
Choose Refactor > Move Inner to Outer Level.
The Move Inner to Outer Level dialog box appears.
In the Class Name field, change the name of the class, if necessary.
(Optional) Select the Declare Field for the Current Outer Class checkbox if you want to generate an instance field for the current outer class and pass the outer class to the constructor. If you select this checkbox, type a name for the outer class' instance field.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the Pull Up command to move methods and fields to a class that their current class inherits from.
To move a class member to a superclass:
In the Source Editor or Projects window, select the class that contains members that you want to move.
Choose Refactor > Pull Up.
The Pull Up dialog box appears and displays a list of the class's members and any interfaces that the class implements.
In the Destination Supertype drop-down list, select the class to which you want to move the members.
Select the checkbox for the member or members that you want to move.
If the current class implements any interfaces, there are checkboxes for these interfaces. If you select a checkbox for an interface, the implements statement for that interface is moved to the superclass.
(Optional) If you want to make a method abstract, select the Make Abstract checkbox for the method. If you select this checkbox, the method will be declared in the superclass as an abstract method and overridden in the current class. The method will be assigned the protected access modifier.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the Push Down command to move inner classes, methods, and fields to all subclasses of their current class.
To move a class member to a subclass:
In the Source Editor or Projects window, select the class member or class members that you want to move.
Choose Refactor > Push Down.
The Push Down dialog box appears and displays a list of the class's members. Make sure the checkbox for the member that you want to move is selected.
(Optional) Select the Keep Abstract checkbox for any abstract methods that you want to keep defined in the current class and have implemented in the subclass. The checkbox in the left column must also be checked for the class definition to be copied to the subclass.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the refactoring Copy command to copy a class.
To copy a class, either to the same or to another package, and to change the code that references that class:
In the Projects window or the Source Editor window, right-click the class and choose Refactor > Copy from the contextual menu.
In the Copy Class dialog box, select the package from the To Package combo box or type the fully qualified package name, such as com.myCom.myPkg
.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
You can also initiate the copying of a class by dragging a class's node in the Projects window to another package's node or by cutting and pasting a class's node.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
To copy a class without doing refactoring:
In the Projects window, manually copy the class to another package.
You can cut and paste the class, or you can use drag and drop.
In the Copy Class dialog box, select the Copy Without Refactoring checkbox.
Click Next.
Field encapsulation is the act of restructuring your code so that a field is accessed only by a pair of accessor methods. Accessor methods are also referred to as read/write methods or getters and setters.
Typically when you encapsulate a field, you change the field's access modifier to private so that the field can not be directly referenced from outside of the class. For other classes to reference the field, they have to use the accessor methods.
Use the Encapsulate Fields command to:
Generate accessor methods for fields. The names of these methods take the form of getfield-
name
and setfield
-name
.
Adjust the access modifier for the fields.
Replace direct references in your code to the fields with calls to the accessor methods.
To encapsulate a field:
In the Source Editor, right-click a field or a reference to the field and choose Refactor > Encapsulate Fields from the context menu.
In the List of Fields to Encapsulate table in the Encapsulate Fields dialog, make sure the checkbox for the field that you want to encapsulate is selected. You can select multiple fields.
(Optional) Set the field's visibility.
(Optional) Set the accessors' (getter and setter) visibility.
(Optional) If you do not want the IDE to replace code to use the accessor methods, clear the Use Accessors Even When Field is Accessible checkbox.
This option only has an impact if both of the following are true:
You have direct references to the field in your code.
You have set the field's accessor modifier so that the field is visible to the classes with these references.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the Change Method Parameters command to alter the signature of a method and have those changes propagated in all of the code that calls this method. Specifically, you can:
Add parameters to a method.
Reorder the parameters in a method signature.
Change the access modifier for the method.
To add a parameter to a method:
Right-click the method in the Source Editor and choose Refactor > Change Method Parameters from the contextual menu.
In the Change Method Parameters dialog, click the Add to add a parameter.
In the Parameters table, modify the name and type of the parameter that you have added. Then add a default value for the parameter in the Value column. You need to double-click a cell to make it editable.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
To reorder a parameter in a method signature:
Right-click the method in the Source Editor and choose Refactor > Change Method Parameters from the context menu.
Select a parameter that you want to move and click Move Up or Move Down to change its position in the list.
Click Next.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
The Refactoring window displays the lines of code that are affected.
Review the list and clear the checkbox of any code that you do not want changed.
Click Do Refactoring to apply the selected changes.
To change a method's access modifier:
Right-click the method in the Source Editor and choose Refactor > Change Method Parameters from the contextual menu.
Choose a modifier from the Visibility Modifier combo box.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
When testing for a logical condition, it can be helpful to replace a Boolean method or variable with an opposite definition.
To invert a Boolean method or variable:
Select the method or variable in the Source Editor.
Choose Refactor > Invert Boolean.
Modify the name of the method or variable in the New Name field.
Click Refactor.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
You can replace a public constructor with references to a newly created builder class. Use the Replace Constructor With Builder command to introduce a builder class that calls the hidden constructor and replaces existing calls to the constructor with calls to the builder class.
To replace a constructor with a builder class:
Select a constructor in the Source Editor.
Choose Refactor > Replace Constructor with Builder
Edit the setter name and default value as needed by double-clicking the appropriate column.
Check the Optional Setter option if you want to omit a setter method in the builder invocation if the default value of a field matches the parameter value in the constructor invocation.
Specify the name of the builder class.
Click Do Refactoring.
You can also replace a public constructor with a factory method. Use the Replace Constructor with Factory command to introduce a new static factory method that calls the constructor and replaces existing calls to the constructor with calls to the new factory method. After replacing a public constructor with a factory method, the constructor is made private.
To convert a constructor into a factory method:
Select a constructor in the Source Editor.
Choose Refactor > Replace Constructor with Factory.
Specify a factory method name.
Click Do Refactoring.
For either operation, you can preview the changes before initiating refactoring. Click Preview and check the items displayed in the Refactoring window. Clear the checkboxes for the parts of the code the you do not want changed. Click Do Refactoring to make the changes.
When you introduce a variable, constant, field, or method in the IDE, you change a selected code fragment into a variable, constant, field, or method. Typically you do this when you want to separate a piece of code into smaller, more meaningful fragments. Creating smaller fragments can increase the reusability of your code as you can separate the parts of your code that may need to be updated more often. By giving your new method a meaningful name, you can increase the comprehensibility of your code.
For example, when you introduce a method in the IDE, you replace statements in a class with a call to a method. Before statements are replaced, the IDE opens the Introduce Method dialog box where you specify the parameters and modifiers for the method. The IDE searches your open projects for occurrences of the statements you specified and replaces the occurrences with the method call.
To introduce a variable, constant, field, parameter, or method:
In the Source Editor, select the statements you want to introduce as a new variable, constant, field, or method.
Choose Refactor > Introduce.
Choose the appropriate menu item, such as Introduce Method.
Type the name for your new item in the Name field and choose the access type.
Provide the information required for the item.
For example, to introduce a method, you must choose an access type.
Select the Replace Also Other Occurrences to replace all occurrences of the selected item with the new reference
Click OK to apply the changes to the selected files.
In situations where you need to add multiple methods to a class but cannot modify the class, you can create a new class that contains these methods. You can this class as a local extension that is either a subclass or wrapper of the original class.
To introduce a local extension:
In the Source Editor, select the class for which you want an extension.
Choose Refactor > Introduce > Local Extension.
The project and source folder name are automatically entered in the dialog box. Use the drop-down list to change the values if needed.
Change the name of the new class to be easily identified.
Specify the name of package to store the extension class.
Select whether the extension class is a wrapper or subclass of the original class.
Select the Equality type if the wrapper option is chosen.
(Optional) Replace all usages of the original class with the extension class throughout the source code.
Troubleshooting
If you encounter an error message when introducing a method, check to see that the statements you selected meet the following criteria:
Selections cannot have more than one output parameter.
Selections cannot contain a break
or continue
statement if the corresponding target is not part of the selection.
Selections cannot contain a return
statement that is not the last statement of the selection. The selected code is not allowed to return conditionally.
Inline refactoring allows you to replace references to a variable, method, or constant with the values assigned to the variable, the implementation of the method, or the constant, respectively.
To inline a variable, constant, or method:
Select a local variable (temp) method, or constant in the Source Editor.
Choose Refactor > Inline.
Click Do Refactoring in the Refactoring window.
Inline Temp replaces all references to a local variable with its initial value and removes the declaration.
Inline Method replaces all method calls with the method's body and removes the declaration.
Inline Constant replaces all constant references with its defined value and removes the declaration.
Use the refactoring Extract Superclass command to extract the common features of classes to create a new superclass. When you extract a superclass, the IDE does the following operations:
Creates a new class with the selected methods and fields in the selected class. You can also have the new class implement interfaces that are implemented in the selected class.
If the selected class extends a class, the new class also extends the same class.
The selected class is modified so that it extends the new superclass. All selected interfaces are removed from the implements clause.
Removes the selected public and protected fields from the base class.
Click Preview in the Extract Interface dialog box to preview the files that are affected. A list of the files to be modified is displayed in the Refactoring window. If you do not want certain occurrences to be changed, you can clear the checkbox for that occurrence in the Refactoring window. Double-clicking on an occurrence opens that file in the Source editor, and the caret is placed in the line containing the occurrence.
To extract a superclass:
Open the class containing the methods or fields you want to move to the new superclass.
In the Source editor, right-click in the file and choose Refactor > Extract Superclass.
The Extract Superclass dialog box opens.
Type the name for your new superclass in the Superclass Name text field.
Select the members you want to extract to the new superclass.
(Optional) If you want to make a method abstract, select the Make Abstract checkbox for the method. If you select this checkbox, the method is declared in the superclass as an abstract method and overridden in the current class. The method will be assigned the protected access modifier.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the Extract Interface command to create a new interface from the selected public non-static methods in a class or interface. Because an interface does not restrict how its methods are implemented, interfaces can be used in classes that have different functions. Creating interfaces can increase the reusability of your code as you can have multiple classes implementing the same interface. If necessary, you can then modify the interface instead of making modifications in multiple classes.
When you extract an interface, the IDE does the following things:
Creates a new interface with the selected methods in the same package as the current class or interface.
Updates the implements or extends clause of the current class or interface to include the new interface. Any interfaces that the new interface extends are excluded.
To extract an interface:
Open the class or interface containing the methods you want to move to an interface.
In the Source editor, right-click in the file and choose Refactor > Extract Interface.
The Extract Interface dialog box opens.
Type the name for your interface in the Interface Name text field.
In the Members to Extract list, select the members that you want to extract to the new interface.
If the class from which you are extracting an interface already implements an interface, there is also an item for that implemented interface. If you select the checkbox for that interface, the implements clause for that new interface is moved to the new interface that you are extracting.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the Use Supertype Where Possible command to replace references to a type with references to one of the type's supertypes. Before replacing those references, the IDE checks to make sure that supertype and its members are accessible to all of the code that would be changed to reference them.
To initiate the Use Supertype Where Possible operation:
In the Source Editor or Projects window, select the type to which you want to apply the operation. The type can be a class, interface, or enumeration.
Choose Refactor > Use Supertype Where Possible.
In the Select Supertype to Use list, select the supertype that you want to be referenced in place of the type your code currently uses.
Click Refactor or Preview.
If you click Refactor, the IDE applies the changes automatically and skips the remaining steps.
If you click Preview, the Refactoring window displays the lines of code that are affected. Review the list and clear the checkbox of any code that you do not want changed. If the class that you are pushing members from has multiple subclasses and you do not want the members to be pushed to all of them, be sure to clear the checkboxes for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
Always perform a clean build after completing any refactoring commands. You can do a clean build by right-clicking the project's node in the Projects window and choosing Clean and Build Project.
Use the Convert Anonymous Class to Inner command to convert an anonymous class to an inner class that contains a name and constructor. When you use this operation, a new inner class is created and the anonymous inner class is replaced with a call to the new inner class.
To use the Convert Anonymous Class to Inner operation:
In the Source Editor, place the insertion point in the anonymous inner class that you want to convert.
Press Alt+Enter and choose Convert Anonymous Class to Inner from the menu that appears.
Use the Safely Delete command to have the IDE check for references to a code element before you delete that code element. You can use this command on classes, methods, and fields.
When you apply the Safely Delete command to a code element, the Safe Delete dialog box opens and helps walk you through the process.
To initiate the Safely Delete operation:
Select the code element that you want to delete and choose Refactor > Safely Delete.
In the Safe Delete dialog box, make sure that the IDE has identified the right element to be deleted and click Next.
If the code element is not referenced by other code, the Safe Delete dialog box closes and the code element is deleted.
If the code element to be deleted is referenced by other code, a warning and a Show Usages button appear in the Safely Delete dialog box. See the following section for information on completing or canceling the operation.
8.11.20.1 Handling Deletions When The Code Element is Referenced
When the message beginning with References to selected elements were found appears in the Safely Delete window, you can proceed in one of the following ways:
Remove the references to the code to be deleted and then continue the Safely Delete operation.
Click Cancel to cancel the command.
If you mistakenly delete a code element that is still referenced by other code, you can reverse the deletion with the Refactor > Undo command.
To remove references to code and continue with the deletion of the class element:
In the Safely Delete dialog box, click Show Usages.
A list of the references to the code that you want to delete is displayed in the Usages window.
Double-click a node for code that references the class to be deleted.
The referencing class opens in the Source Editor.
Remove the reference to the code that you want to delete.
Use the Safely Delete command to remove this reference. If there are references to that code as well, you can click Show Usages to open a new tab in the Usages window.
Repeat steps 2 and 3 until all references to the code that you want to delete are removed.
In the Usages window, click Rerun Safe Delete.
The Safely Delete command is run again. If there are any references that you have not removed, a warning appears and you can click Show Usages to resume the process of resolving the references.
Click Preview in the Safe Delete window, then click Next.
Click Do Refactoring in the Refactoring window to proceed with the deletion.
In the Source Editor, a hint is displayed when the IDE performs source code analysis and detects common syntax errors or problems.
An editor hint is available if a light bulb icon appears in the left margin of the Source Editor while you are developing your code. Click the light bulb icon or press Alt+Enter to read the hint. Click the hint or press Enter to generate the code suggested by the hint.
Note:
You can select which hints to display when you type in the Source Editor in the Hints tab of the Editor panel in the Options dialog box. You can access it by choosing Tools > Options from the main IDE's menu, and then clicking the Editor category.
You can use hints when running source code inspections on a selected file, package, or project and refactoring your sources.
To initiate the Inspect operation:
Choose Source > Inspect from the main IDE's menu.
In the Scope drop-down list of the Inspect dialog box, select a file, package, or project(s) to be inspected.
Select either of the following:
In the Configuration drop-down list, select NetBeans Java Hints to choose all hints available in the IDE to be used in the source code analysis.
Alternatively, click Manage to open the Configurations dialog box and specify a set of hints to be used in the source code analysis. Click OK.
Select Single Inspection and choose a single hint to be used in the source code analysis.
Click Inspect to perform the source code analysis.
After the Inspect operation is completed, the hints that can be applied to your code are displayed in the Inspector Window below the Source Editor.
To initiate the Inspect and Transform operation:
Choose Refactor > Inspect and Transform from the main IDE's menu.
In the Inspect drop-down list of the Inspect and Transform dialog box, select a file, package, or projects to be inspected.
Alternatively, click the button to the right to open the Custom Scope dialog box and specify the custom code to be inspected.
Select either of the following to use:
In the Configuration drop-down list, select a predefined configuration of hints available in the IDE (for example, Convert to JDK 7
) to be used in the source code analysis.
Alternatively, click Manage to open the Manage Inspections dialog box and group a set of hints into a configuration to be used in the source code analysis. Click OK.
Select Single Inspection and choose a single hint to be used in the source code analysis.
Click Refactor to run the source code analysis.
After the Inspect and Transform operation is completed, the results are displayed in the Inspect and Transform dialog box. Click Preview to display the source code refactorings proposed by the IDE upon conducting the source code analysis with the hints you specified.
Check the complete list of hints available in the IDE at the Java Hints wiki page at http://wiki.netbeans.org/Java_Hints
.
For information on how to create a NetBeans module that provides one or more Java hints, see the NetBeans Java Hint Module Tutorial at https://platform.netbeans.org/tutorials/nbm-java-hint.html
.
Refactoring is especially useful in EJB modules, since changing the name of one method often means you have to update the name in all of the related interfaces, deployment descriptors, and dependent classes and servlets.
To refactor an EJB module:
Right-click a piece of code in the Source Editor and choose from the Refactor submenu in the pop-up menu.
You cannot move an enterprise bean or any of its classes and interfaces to a different project. The Move Class command only lets you move bean classes and interfaces to different packages in the same EJB module.
You cannot rename mandatory EJB infrastructure methods such as ejbCreate
.
When you rename a Web service endpoint interface, the IDE updates the corresponding WSDL file.
When deleting a code element, you can use the Safely Delete refactoring command to help check for references to that element before making the changes.
When using Maven as the build infrastructure for Java projects, Maven uses conventions and patterns to provide a uniform build system. All Maven projects use a shared set of plugins that are retrieved from the Maven repository and Maven executes a defined series of tasks as part of the lifecycle when building the project. Unlike Ant, you do not need to explicitly specify all the tasks required for building a project.
Maven support in the IDE includes the following features:
Maven is bundled with IDE and is used to run builds
Project creation from archetypes in the New Project wizard
Repository browser for managing Maven repositories
Code-completion for POM in editor
Configuring of custom Maven goals
For information about developing projects in the IDE using Maven, see the Maven best practices page at http://wiki.netbeans.org/MavenBestPractices
.
For more information about using Maven, see the Maven documentation at http://maven.apache.org
.
The New Project wizard enables you to create a new Maven project (referred to as an artifact) based on an archetype in your local or a remote repository. An archetype is a Maven project template. When you create the new artifact, the wizard prompts you to specify the project coordinates (artifactId, groupId, versionId).
To create a new Maven project:
Choose File > New Project from the main menu to open the New Project wizard.
Choose the Maven category and then choose a Maven project template.
Click Next.
Specify the project name, location and project details. Click Finish.
The IDE creates the Maven project and displays the node for the project in the Projects window.
When using Maven, be aware of the following considerations:
If you have only recently installed Maven, the first time you create a project the IDE might need to download the most recent artifacts into your local repository. This process can take some time.
If you choose an Enterprise Application template, the IDE automatically creates an assembly module for packaging the web application module and EJB module. You can select the modules that you want to create in the New Project wizard.
If you choose a NetBeans Application template, you can choose to use OSGI bundles if the version of NetBeans you are using supports it and whether you want the IDE to create a NetBeans module and configure it as dependency of the project.
If you choose the Project from Archetype project template, you need to choose an archetype. The wizard displays the available archetypes contained in your local or registered remote repository.
If you have an existing Maven project that contains a pom.xml
file, you do not need to use the New Project wizard. You can open the project by choosing Open Project (Shift+Ctrl+O) from the main menu.
After you create the project, you can configure additional project properties by right-clicking the project node in the Projects window and choosing Properties.
Configure Maven settings at the IDE level and at the project level. At the IDE level, you can configure Maven installation and repository details and define global Maven goals. At the project level, you can create configurations to activate Maven profiles and bind IDE actions to Maven goals for a project.
8.12.2.1 Configuring Maven Settings for the IDE
Configure Maven settings that affect the behavior of Maven in the IDE in the Options window. You can specify a local Maven installation, the location of the local Maven repository, and settings for updating the repository.
To modify Maven settings in the IDE:
From the main window, choose Tools > Options.
Click the Java option and then click the Maven tab.
Modify the properties as desired.
Click OK.
8.12.2.2 Configuring Maven Settings for Projects
By using the project's Properties window, you can configure Maven settings for an individual project. You can create custom configurations and then bind IDE actions to Maven goals and assign the binding to a configuration.
To configure Maven settings for a project:
Right-click the project node in the Projects window and choose Properties.
Click the category in the left pane and modify the properties in the right pane.
8.12.2.3 Using Project Configurations
The Configurations category of the Project Properties window of a Maven project enables you to create and select custom configurations for your project. For example, you can create custom configurations to do the following:
Load the project in the IDE with a customized set of dependencies or submodules.
Trigger actions and activate any associated profiles.
Customize IDE actions to map to Maven goals.
To create a custom configuration for a project:
Open the Configurations category of the Properties window by right-clicking the project node in the Projects window and choosing Set Configuration > Customize.
Alternatively, right-click the project node and choose Properties and select Configurations in the Project Properties window.
Click Add to open the Add Configuration dialog box.
Alternatively, select an existing configuration and click Clone to create a copy of the configuration. The name of the clone configuration is the name of the original configuration with the suffix _clone
. You cannot rename the clone but you can set profiles and properties.
Type a name for the new configuration.
Select Keep private to this IDE instance if you do not want to share the configuration with other instances of the IDE.
By default this option is deselected and configurations are shared between instances of the IDE when the project is opened, for example when you open the project in an updated version of the IDE.
Type any profiles or settings that you want to enable for the configuration. Click OK to close the Add Configuration dialog box.
Select the new configuration in the list of configurations and click Activate.
The name of the configuration that is currently active is in bold.
Modify additional options for the configuration in the other categories in the Properties window.
Click OK.
When you click OK the IDE creates a configuration file in the root directory of the project with the name nbactions-myconfigurationname.xml
.
To activate a configuration for a project, right-click the project node and choose Set Configuration and then choose the configuration name in the context menu. You can also use the drop-down list in the toolbar to switch between configurations for the project that is currently selected in the Projects window. If a project is set as the main project, the dropdown list displays the configurations for the main project.
8.12.2.4 Binding IDE Actions to Maven Goals
Use the Actions category in the Properties window to customize IDE actions by binding the action to Maven goals. The Actions pane lists the IDE's default project actions that can be mapped to Maven goals. Assign the mapping to a project configuration if you activated configurations for the project.
After you select an IDE action, modify the Maven goals and properties of the action by typing in the textfield. Actions are displayed in bold if the default values for the action have been modified. The following textfields display the goals and properties associated with the selected action:
Execute Goals. This field displays the Maven goals that are associated with the selected IDE action.
Activate Profiles. This field displays any profiles that are activated when the action is invoked.
Set Properties. This field displays the properties that are set on the command line. Properties are generally used to customize the behavior of the executed goal.
Type in the text area to add a property or click the Add button to view and add one of the default properties.
When you select an action you can select the Build with Dependencies checkbox if you want to run the Build with Dependencies command as part of the action.
8.12.2.5 Creating Custom Actions
Click Add Custom in the Actions category of the Properties window to create custom actions for a project. After you create the new action, specify the goals or properties for the new action. Right-click the project node in the Projects window and choose the action under Custom in the context menu to invoke the new action.
Click Edit Global Custom Goal Definitions in the Maven tab in the Options window to create global custom goals for Maven projects. The global goal is then listed in the context menu under Custom when you right-click a Maven project in the Projects window.
The Project Object Model (POM) is the basic unit of work in Maven. The POM is described in the pom.xml
XML file and contains project and configuration details, such as the artifact coordinates, project dependencies, and build profiles that Maven uses to execute goals and build the project.
For more information about POM elements, see Introduction to POM at http://maven.apache.org/guides/introduction/introduction-to-the-pom.html
.
When you use the New Project wizard to create an artifact, the IDE automatically generates the pom.xml
file and adds the artifact details. Open pom.xml
in the XML editor to edit the file. The following features are available in the XML editor to help you edit pom.xml
:
Code completion. The IDE's code completion can help you add and modify elements. The code completion hints offered in the editor are based on the contents of the repository.
Insert Code. The IDE can generate XML elements for you based on the details you specify in a dialog box. When you right-click in the editor window and choose Insert Code (Ctrl-+), a context menu appears where you can choose to add any of the following types of elements to the POM:
Dependency
Dependency Exclusion
Plugin
Profile
License
After you select the type of element a dialog box opens that enables you to specify the details about the code that you want the IDE to insert into the POM:
Dependency Graph. The Maven Dependency Graph is a visual representation of the direct and transitive dependencies specified in pom.xml
. Click the Graph tab in the XML editor toolbar to open the graph. You can select any element in the graph to view a representation of the dependencies of that element. You can right-click in the graph view and choose different layout schemes in the popup menu.
Effective POM. The Effective POM tab displays a read-only version of the POM that Maven uses to build the project after other factors that affect the build such as any active profiles and inherited parent POMs are incorporated. The left column of the tab displays the source that generates each line in the effective POM when the source can be determined. Right-click the source and choose Go to Source to navigate to the line in the source where the element is specified.
In the Effective POM tab you can click Show Diff in the toolbar to compare the effective POM to a POM for an alternate project configuration or profile. Click Show Diff to open a dialog box where you can select the alternate POM. The diff of the POMs opens in a new tab in the IDE.
To make libraries and projects available to your project during compilation, testing, and execution, you need to declare the projects or libraries as dependencies. All dependencies need to be available as artifacts in your local repository when you build the project.
You declare a dependency by modifying the POM to add the coordinates of the artifact you want to declare as a dependency. All Maven artifacts are defined by a unique coordinate that consists of a group identifier (groupId), artifact identifier (artifactId) and version. Adding a dependency to the POM is similar to adding libraries to the classpath in an Ant-based project.
To add a dependency to a Maven project:
Edit the POM in the editor. Open pom.xml
in the XML editor and use code completion to help you write the dependency elements and artifact coordinates.
Use the Add Dependency dialog. Type or search for the artifact in the Add Library dialog and click OK. When you click OK, the IDE adds the dependency elements and artifact coordinates to pom.xml
.
To open the Add Dependency dialog:
Right-click the Dependencies node in the Projects window and choose Add Dependency.
Right-click in pom.xml
in the editor and choose Insert Code (Ctrl+I) and choose Dependency.
Right-click an artifact under the Maven Repositories node in the Services window and choose Add as Dependency and select a project in the Add Dependency dialog box.
After you add a dependency to pom.xml
, a node for the artifact ( ) appears under the project's Dependencies node. Artifacts that are not in your local repository are marked with a badge. You need to have a copy of the artifact in your local repository if you want to use it in your project. This applies to libraries and to other projects that are described as dependencies.
Note:
If a required artifact is available in a remote repository, Maven automatically downloads the artifact and any transitive dependencies from the repository when you build the project. Maven uses the latest available version of the artifact if no version is specified. If the required artifact is not available in a remote repository, right-click the artifact node and install the artifact manually.
It is recommended that you store Maven software library JARs and project artifacts in a local repository and keep the source code for projects under a version control system.
The project dependencies that are displayed under a project's Dependencies node are Maven artifacts. Each Maven artifact has a unique coordinate (groupId, artifactId and version) that is used to identify the artifact in a project's POM. An artifact can also have dependencies. The artifacts available to a project can be viewed under the Maven Repositories node in the Services window.
Right-click an artifact in the Projects window or the Services window to invoke a popup menu with commands for downloading the sources and Javadoc of an artifact, finding usages and viewing artifact details. Use the Artifact Viewer to view details about individual artifacts.
To open the Artifact Viewer, perform either of the following steps.
In the Projects window, right-click an artifact under the Dependencies node and choose View Artifact Details.
In the Services window, expand the Maven Repositories node, right-click an artifact and choose View Details.
The Artifact Viewer displays details in the following tabs:
Basic. Displays the artifacts coordinates and version details.
Project. Displays metadata contained in the artifact's POM such as the description of the artifact, the URL for the project and issue tracking and version control details.
Classpath. Displays the artifact's compilation, runtime and test dependencies.
Graph. Displays a visualization of the artifact's primary and secondary dependencies.
POM. Displays the pom.xml file of the artifact.
Table 8-1 describes the commands available from the toolbar of the Artifact Viewer:
Table 8-1 Artifact Viewer Toolbar Commands
Command | Description |
---|---|
Add as Dependency |
Opens the Add Dependency dialog box from which you can choose a project. |
Checkout Sources |
Opens the Checkout Sources wizard in which you can specify a location for a local repository for the sources. Use this command only if the sources of the artifact are available in a repository |
Create Library |
Creates a NetBeans library from the artifact. The new library is available in the Ant Library Manager. |
8.12.5.1 Visualizing Dependencies
The Graph tab of the Artifact Viewer enables you to easily visualize dependencies. The visualizer also provides tools to help you find and resolve potential problems resulting from dependency version conflicts.
To use the graph view to resolve dependency conflicts:
Open the artifact in the Artifact Viewer and click the Graph tab.
Alternatively, you can open pom.xml
file in the editor and click the Graph tab.
Locate any artifact boxes that have a red background.
In the dependency graph, a dependency with a red background indicates a potential version conflict.
Click the suggestion icon to open a dialog box with a description of the conflict and options for resolving the conflict.
The Maven build lifecycle has defined phases with goals that are executed when building and distributing the project. When you execute a goal, Maven will also execute all the preceding goals in the build lifecycle. You can invoke phase goals and plugin goals by mapping the goals to IDE actions, or you can create custom goals and invoke the goals individually. When you execute a goal, the Maven output with the plugin and goal identifiers are displayed in the Output window.
When you want to generate distributable files for the project, such as JAR files or WAR files, you need to build the project. When you build a Maven project using the IDE's Build command, by default the IDE executes the plugin goals in the install phase of the Maven lifecycle (builds the project and adds the artifact to the local repository).
Note:
The IDE can automatically compile classes when you save them if you enable the Compile on Save option in the Compile category of the project's Properties window. When Compile on Saveis enabled, you do not need to build the project or compile individual classes to run or test the project in the IDE. The incrementally compiled files are stored in a cache in your user directory and are copied to your project's build folder when you run or debug your project.
Compile on Save is enabled by default for WAR, EJB and EAR projects.
To build a Maven project:
Select the project node in the Projects window.
Choose Run > Build Project (F11).
When you build a project the IDE displays the Maven output and any compilation errors in the Output window. You can double-click any error to go to the location in the source code where the error occurred.
You can click Show Build Overview ( ) in the Output window sidebar to open the Build Execution Overview window to view additional details about the executed goal or goals. Click Show Phase in the Build Execution Overview window to view the goals organized by the phase in the build lifecycle. You can right-click a goal in the Build Execution Overview window to open a popup menu where you can choose to view the goal definition in the POM, the source code of the plugin or to debug the plugin.
You can modify the goals that are executed by the Build command and other IDE commands by modifying the Maven settings in the project's Properties window.
To build an individual project and its required projects:
Right-click the project's node in the Projects window and choose Build with Dependencies.
Note:
You can change the default Build action to Build with Dependencies by selecting the Build action in the Actions category of the project's Properties window and then selecting the Build with Dependencies checkbox.Modify the project dependencies by adding libraries in the Projects window or by editing pom.xml
in the editor.
8.12.6.1 Executing Maven Goals in the IDE
IDE actions in the popup menu are mapped to Maven phases and goals. For example, by default the Build action in the IDE is mapped to the install phase in the Maven lifecycle. When you right-click the project node and choose Build, the IDE executes the goals described in the install phase to package the project and executes all the goals in the preceding phases in the build lifecycle.
You can modify the mapped Maven goals that are invoked by IDE actions by configuring actions in the project's Properties window or in the Maven tab in the Options window. For more information, see Section 8.12.2, "How to Configure Maven Settings."
8.12.6.2 Customizing the Build Process
To customize the build for a Maven project, modify the POM to add or reconfigure plugins and dependencies. You can use the code completion in the editor to help you when adding details to pom.xml
.
To customize a build:
Open pom.xml
in the XML editor.
Choose Source > Insert Code (Ctrl+I) from the main menu and select Plugin from the popup menu to open the Add New Plugin dialog box.
Type a query term to search for the plugin.
Select the plugin from the list of available plugins.
Select the goals that you want to be executed. Click OK.
When you click OK, the IDE adds the plugin description to pom.xml
and the goals to run as part of the build process. If you add a plugin that is not in the local repository, the required artifact will be automatically downloaded from a remote repository when required.
8.12.6.3 Executing Individual Goals
If you select the project node or pom.xml
in the Projects window you can execute goals that are defined in the pom.xml
from the Navigator window.
To execute a goal:
Open the Navigator window.
Select the project node in the Projects window.
Alternatively, select pom.xml
in the Projects window and choose Related goals in the drop-down list at the top of the Navigator window.
Right-click a goal in the Navigator window and choose Execute Goal.
Alternatively, select Execute Goal with Modifiers to open the Run Maven dialog box and modify the default run settings for the goal.
You can view the results of the goal in the Output window.
Software library archives (JARs), build artifacts and dependencies that are used to build Maven projects are stored in repositories. There are two types of repositories:
Local repositories. A cache of a remote repository that is stored on the local machine. Maven projects are built against the local repository. The local repository usually only stores a subset of the files available in the remote repository and any temporary build artifacts.
Remote repositories. A repository that contains all the Maven artifacts and plugins. The remote repository may be a third-party repository (for example, http://repo.maven.apache.org/
), or it may be a private internal repository.
The IDE indexes the contents of local and remote Maven repositories using the Nexus indexing engine. The IDE uses the repository indexes for some Maven-related functions such as code completion. You can browse and manage Maven repository indexes in the Services window.
To browse Maven repositories:
Choose Window > Services from the main menu and expand the Maven Repositories node to view the contents of the repositories.
The Maven Repositories node in the Services window lists the Maven repositories registered with the IDE and enables you to add, remove and update Maven repositories. The local Maven repository is indicated by a yellow repository node ( ) and remote repositories are indicated by blue repository nodes ( ).
By default, the IDE includes the central Maven repository in the list of remote repositories. When a project requires build artifacts that are not stored in the local repository, Maven downloads the required artifacts to the local repository from a remote repository. The files in the local Maven repository are then shared by all of your Maven projects.
Expand the repository nodes to view the indexed artifacts grouped by GroupId and ArtifactId, the version of the sources, and the type of packaging. Depending on the metadata available, right-click an artifact to perform the following actions:
View Details. Opens the Artifact Viewer tab in the editor window.
Add As Dependency. Adds the library to an open project as a dependency. The IDE automatically modifies the project's POM.
Find Usages. Displays open projects and repository artifacts that use the selected library as a dependency.
View JavaDoc. Displays the downloaded JavaDoc in a browser.
Open. Opens the project POM in the IDE.
Download. Downloads the artifact to the local Maven repository.
Download Sources. Downloads the source JAR for the binary. After downloading, if you click on a class file, the Java file is displayed.
Download JavaDoc. Downloads the Javadoc.
Copy. Copies the dependency.xml
snippet of the artifact to the clipboard, which you can paste into the project pom.xml
file.
To locate artifacts in the repositories:
Right-click the Maven Repositories node and choose Find.
Enter the search term for the artifact in the Find in Repositories dialog box (a groupID, for example) and select any additional criteria.
Click OK.
When you click OK the IDE creates a node for the search term ( ) under the Maven Repositories node. Expand the search node to view a list of the artifacts that matched your search. Remove a search node by right-clicking the node and choosing Delete.
To add a repository:
Right-click the Maven Repositories node and choose Add Repository.
Specify the details for the new repository and click Add.
https://docs.oracle.com/netbeans/nb82/netbeans/NBDAG/build_japps.htm#NBDAG2116