Creating and editing Java source code is
the most important function that the IDE serves, since that's what
developers generally spend most of their day doing. NetBeans IDE
provides a wide range of tools that can complement any developer's
personal style, regardless of whether you prefer to code everything by
hand or want the IDE to generate large chunks of code for you.
This section covers the following topics:
Creating Java Files
NetBeans IDE contains templates and wizards
that you can use to create all kinds of source files, from Java source
files to XML documents to resource bundles.
Perhaps the easiest way to create a file
(once you have already created a project) is to right-click the project
node of the project for which you want to create the file in the
Projects window. You can then choose the desired file type from the New
pop-up menu when you right-click the project node. The New submenu
contains shortcuts to commonly-used templates and a File/Folder command
that you can use to open the New File wizard and access all NetBeans
templates.
Choosing a template from the New menu
The New File wizard enables you to create a
new file based on the IDE's default file templates. The file templates
are grouped by type. In addition to the default file templates, you can
customize the templates the IDE uses to create files and also create
your own templates. Having the option to use your own templates can be
useful if a certain file type needs to have standard elements, or you
want to change the way other elements are generated. When you create
your own templates, you can make them available in the New File wizard.
Using File Templates
You use the Template Manager to modify and
create new templates by choosing Tools from the main menu and choosing
Template Manager. You can create a new template by copying an existing
template and then clicking Edit. For example, if you want to create a
new Java class template, you can duplicate an existing Java class
template, then select the new class and then click Open in Editor. You
can now modify the class in the Source Editor and save it. The new
class is now available in the New File wizard.
If you have an existing template that you
would like to add to the IDE, click Add and locate the file on your
system. The file is now available as a template in the New File wizard.
Using GUI Templates
If you want to visually edit a Java GUI
form using the IDE's GUI Builder, you have to create the form's source
file using the IDE's Java GUI Forms templates. This template group
contains templates for AWT and Swing forms. For example, you cannot
create a normal Java class file and then change it to extend JPanel and
edit it in the GUI Builder.
For more information about creating Java GUIs in the IDE, see the following:
Editing Java Files in the Source Editor
The Source Editor is your main tool for
editing source code. It provides a wide range of features that make
writing code simpler and quicker, like code completion, highlighting of
compilation errors, syntax highlighting of code elements, as well as
other advanced formatting and search features.
Although the Source Editor can be
considered a single IDE component, it is really a collection of
editors. Each type of source file has its own editor that provides
different functionality. In this section we'll be dealing with the Java
editor, but many of the same concepts apply to other editors. To open a
Java source file in the Source Editor, double-click the file's node in
the Projects window or Files window.
The IDE has many mechanisms for generating
different types of code snippets. The following mechanisms are some of
the most commonly used.
-
Code Completion
(Ctrl-Space). When you are typing your code, you can use the shortcut
to open up the code completion box. The code completion box contains a
context-sensitive list of options to complete the statement you are
currently typing. Continue to type additional characters to narrow down
the number of options presented in the code completion box.
-
Code Templates.
For many commonly used code snippets you can use multi-keystroke
abbreviations instead of typing the entire snippet. The IDE expands the
abbreviation into the full code snippet after you press the spacebar.
-
Editor Hints
(Alt-Enter). If the IDE detects an error, such as missing code, the IDE
can suggest missing code to fix the error, and then insert that code
where necessary. When the insertion point is in the line marked as
containing an error, the IDE displays a lightbulb icon in the margin to
indicate a suggested fix for that line. Use the keyboard shortcut or
click the lightbulb to display the suggestion. Select the hint you want
and press Enter to have the fix generated in your code.
The following topics illustrate how to get the most out of these features.
Code Completion
When typing Java identifiers in the Source
Editor, you can use the IDE's code completion box to help you finish
expressions. When the code completion box appears, a box with Javadoc
documentation also appears displaying any documentation for the
currently selected item in the code completion box. You can disable the
Javadoc box in the Options window.
Code completion example
You can use the code completion box to generate a variety of code, including the following:
-
Fill in the names of classes and class members, as well as any necessary import statement.
-
Browse Javadoc documentation of available classes.
-
Generate whole snippets of code from dynamic code templates. You can customize code templates and create new ones. See Configuring the Editor below for more information.
-
Generate getter and setter methods.
To open the code completion box, type the
first few characters of an expression and then press Ctrl-space.
Alternately, you can open the code completion box by pausing after
typing a period (.) in an expression. The code completion box opens
with a selection of possible matches for what you have typed so far.
You can narrow the selection in the code completion box by typing
additional characters in the expression.
To use the code completion box to complete
the expression, continue typing until there is only one option left and
press Enter, or scroll through the list and select the option you want
and then press Enter. To close the code completion box without entering
any selection, press Esc. To turn off code completion in the Source
Editor, see Configuring the Editor.
The IDE uses the classes on your
compilation classpath to provide suggestions for code completion and
other features. Classes from the target JDK version, other commonly
used project-specific APIs like the Servlet, JSP, JSTL and XML APIs, as
well as the sources you have manually added to the classpath can be
used in code completion. For details, see Managing a Project's Classpath.
Code Templates
You can use code templates to speed up the
entry of commonly used sequences of reserved words and common code
patterns, such as for loops and field declarations. The IDE comes with
a set of templates, and you can create your own code templates in the
Options window. For more on how to configure how code templates are
implemented in the Source Editor, see Configuring the Editor. For more on the syntax used for creating your own code templates, see Special Code Template Syntax.
A code template can be composed of bits of
commonly used text, or it can be more dynamic, generating a skeleton
and then letting you easily tab through it to fill in the variable
text. Where a code snippet repeats an identifier (such as an object
name in an instance declaration), you just have to type the identifier
name once.
For example, if you enter
forc
and press the space bar, it expands into
for (Iterator it = collection.iterator(); it.hasNext();) {
Object elem = (Object) it.next();
}
Once the code is expanded in the Source Editor, you can simply press tab to jump to the next variable in the code snippet.
If an abbreviation is the same as the text
that you want to type and you do not want it to be expanded into
something else, press Shift-spacebar to keep it from expanding.
You can access code templates by doing the following in the Source Editor:
-
Typing the first few letters of the code,
pressing Ctrl-spacebar, and then selecting the template from the list
in the code completion box. The Javadoc box displays the full text of
the template.
-
Typing the abbreviation for the code
template directly in the Source Editor and then pressing the spacebar.
You can find the abbreviations for the built-in Java code templates by
opening the Editor settings in the Options window and choosing the Code
Templates tab.
Special Code Template Syntax
When you create code templates, there are
several constructs that you can use to customize the way the code
template behaves. The Special Code Template Syntax table lists the most useful of these constructs. You can look at the default IDE code templates for the abbreviations
fori
,
forc
, and
newo
in the Source Editor Abbreviations for Java Files table to see these constructs in action.
Editor Hints
When the IDE detects an error for which it
has identified a possible fix, a lightbulb icon appears in the left
margin of that line. You clan click the lightbulb or press Alt-Enter to
display a list of possible fixes. If one of those fixes suits you, you
can select it and press Enter to have the fix generated in your code.
Often, the "error" is not a coding mistake
but a reflection of the fact that you have not gotten around to filling
in the missing code. In those cases, the editor hints simply automate
the entry of certain types of code.
Refactoring
Refactoring is the restructuring of code,
using small transformations, in which the result does not change 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. 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 to promote understanding
-
Removing unnecessary repetition
-
Enabling use of the code for alternate or more general needs
Most refactoring commands are accessible
from the Refactor menu on the main menu bar. You can also right-click
in the Source Editor or on a class node in the Projects window and
choose a command from the Refactor submenu. You can use the Undo
command to roll back all the changes in all the files that were
affected by the refactoring.
The IDE provides the following features to facilitate code refactoring:.
Command
|
Description
|
Find Usages
|
Finds all occurrences of the name of the specified class, method, or field.
|
Rename
|
Enables you to rename all occurrences of a
class, variable, or method to something more meaningful. In addition,
it updates all source code in your project to reference the element by
its new name.
|
Safely Delete
|
Deletes a code element after making sure that there are no references to that element in your code.
|
Change Method Parameters
|
Enables you to change the parameters and the access modifier for the given method.
|
Encapsulate Fields
|
Generates accessor methods (getters and
setters) for a field and optionally updates all referencing code to
access the field using the getter and setter methods.
|
Move Class
|
Enables you to move a class into another
class or package and to move a static field or a static method from one
class to another. In addition, it updates all effected source code in
your project to reference the element in its new location
|
Pull Up
|
Moves a method to a class's superclass. You
can also use this command to declare the method in the superclass and
keep the method definition in the current class.
|
Push Down
|
Moves a method to a class's subclass. You
can also use this command to keep the method declaration in the current
class and move the method definition to subclass.
|
Extract Method
|
Creates a new method based on a selection
of code in the selected class and replaces the extracted statements
with a call to the new method.
|
Extract Interface
|
Creates a new interface based on a
selection of methods in the selected class and adds the new interface
to the class's implements clause
|
Extract Superclass
|
Creates a new superclass based on a
selection of methods in the selected class. You can have the class
created with just method declarations, or you can have whole method
definitions moved into the new class.
|
Use Supertype Where Possible
|
Change code to reference objects of a superclass (or other type) instead of objects of a subclass.
|
Move Inner to Outer Level
|
Moves a class up one level. If the class is
a top-level inner class, it is made into an outer class and moved into
its own source file. If the class is nested within the scope of an
inner class, method, or variable, it is moved up to the same level as
that scope.
|
Convert Anonymous Class to Inner
|
Converts an anonymous inner class to a named inner class.
|
Working With Import Statements
In the IDE, there are several ways to help you make sure that your Java class has all the necessary import statements:
-
For the whole file, by pressing Alt-Shift-F (Fix Imports) when the insertion point is in the file in the Source Editor.
-
Individually, by pressing Alt-Shift-I (Fast Import) when the insertion point is in the referenced class name in your code.
-
If you use code completion to fill in the
name of class, any necessary import statements are automatically added.
You can also use code completion to use a customized code template. You
can modify the variables in the custom code template to add the
required import statement when that template is used.
-
If suggested as an editor hint in the IDE,
you can click the lightbulb icon in the margin to add the suggested
import statements.
The IDE's Fix Imports command adds import
statements that are needed by your code and removes unused import
statements. It does not, however, remove fully-qualified class names
from code and replace them with import statements. The Fast Import
command, on the other hand, enables you to choose how you want the
import handled in your code.
The IDE's Fast Import command enables you to:
-
Generate an import statement for the class.
-
Generate an import statement for the package.
-
Generate a fully qualified name in the code.
Formatting Java Source Code
The IDE automatically formats your code as
you write it. You can also reformat specific lines of code or even
entire files. The following table lists some common formatting commands.
Keyboard Shortcut
|
Description of Command
|
Ctrl-Shift-F
|
Reformat the entire file or whatever text is selected in the Source Editor.
|
Ctrl-T
|
Shift the current line or selection one tab to the right.
|
Ctrl-D
|
Shift the current line or selection one tab to the left.
|
Ctrl-E
|
Remove the current line.
|
Ctrl-Shift-T
|
Comment out the current line or all selected lines with line comments ("//").
|
Ctrl-Shift-D
|
Remove comments. This command only works for lines that begin with line comments ("//").
|
Navigating in the Source Editor
When you are dealing with a large group of
files, the ability to quickly navigate within and between source files
is critical to your productivity. When you are working in a document in
the Source Editor, the Navigate menu contains commands that enable you
to quickly jump to elements within a document according to the
currently selected element, as well as between documents.
Navigating Within a Java File
The IDE provides several mechanisms to make it easier to view and navigate a given Java file:
-
Navigator window.
The Navigator window appears below the Projects window and provides a
list of members (for example, constructors, fields, and methods) in the
currently selected Java file. When you click on an element, the
insertion point is placed at the line containing that element in the
Source Editor.
-
Bookmarks.
You can create bookmarks in your source file to help you easily jump
back to specific places in the file. You can toggle bookmarks on and
off by right clicking the line in the margin of the file or by choosing
Toggle Bookmark (Ctrl-F2) in the Navigate menu. You can move between
those places where your insertion point has been by using the Alt-K and
Alt-L keyboard shortcuts, or by choosing Back or Forward in the
Navigate menu.
-
Navigate Menu.
Use the Navigate menu to access commands for quickly navigating between elements in your code.
The following table lists shortcuts to some commands in the Navigate menu.
Keyboard Shortcut
|
Description of Command
|
Alt-Shift-O
|
Go to Class.
Opens the Fast Open dialog box, which lets you quickly open a file.
Start typing a class name in the dialog box. As you type, all files
that match the typed prefix are shown.
|
Alt-O
|
Go to Source.
Jumps to the source code for the currently selected class, method, or
field, if the source is available. Alternately, you can hold down the
Ctrl key and hover the mouse over the identifier and then click the
identifier when it is underlined in blue.
|
Alt-G
|
Go to Declaration.
Similar to the previous shortcut, this opens the file where the variable at the insertion point is declared.
|
Ctrl-B
|
Go to Super Implementation.
Jumps to the super implementation of the currently selected method (if
the selected method overrides a method from another class or is an
implementation of a method defined in an interface).
|
Alt-L
|
Forward. Go
to the next location in the jump list for the currently selected file.
The jump list is a history of all locations where you made
modifications in the Editor.
|
Alt-K
|
Back.
Go to the previous location in the jump list for the currently selected file.
|
Ctrl-G
|
Go to line.
Enter any line number for the current file and press Enter to jump to that line.
|
Ctrl-F2
|
Toggle Bookmark.
Add a bookmark (bookmark icon) to the line of code that the insertion
point is currently on. If the line already contains a bookmark, this
command removes the bookmark.
|
F2
|
Next Bookmark.
Go to the next bookmark.
|
Shift-F2
|
Previous Bookmark.
Go to the previous bookmark.
|
Alt-Shift-L
|
Go to the next jump list location in all files (not the currently selected file).
|
Alt-Shift-K
|
Go to the previous jump list location in all files (not the currently selected file).
|
Search and Selection Tools
The following list gives you a quick overview of the search and selection tools that are available in the Source Editor:
Keyboard Shortcut
|
Description of Command
|
Ctrl-Shift-O
|
Switch to the Search Results window.
|
Ctrl-Shift-P
|
Find in Projects.
|
Ctrl-F
|
Search for text in the currently selected
file. The Source Editor jumps to the first occurrence of the string and
highlights all matching strings.
|
Ctrl-H
|
Replace text in the currently selected file.
|
F3
|
Find the next occurrence of the word you searched for.
|
Shift-F3
|
Find the previous occurrence of the word you searched for.
|
Ctrl-F3
|
Search for the next occurrence of the word that the insertion point is on.
|
Alt-Shift-H
|
Toggle on/off search result highlighting.
|
Navigating Between Documents
The Source Editor makes it easy to manage
large number of open documents at one time. Each open document is
represented by its own tab in the area directly below the IDE's
toolbar. The tabs appear in the order in which you opened the
documents, however, you can change a tab's position by simply grabbing
and dragging it to the desired location along the row of tabs. Use the
left and right buttons in the top-right corner to scroll through the
row of tabs.
To switch between open files, do any of the following:
-
Use the drop-down list at the top-right of
the Source Editor. The drop-down list displays all of your open files
in alphabetical order.
-
Press Alt-Left and Alt-Right to move one editor tab to the left or right.
-
Press Ctrl-Tab to open the IDE window
manager, which contains icons for each open document in the Source
Editor as well as all open windows like the Projects window.
Other useful IDE features that assist you in navigating your documents include:
-
Go to Class.
Choosing Go to Class in the Navigate menu opens up a dialog box
enabling you to quickly locate a class by name. When you choose a class
the source file is opened in the Source Editor.
-
Maximize the Source Editor.
Double-click any document tab or press Shift-Escape to hide all other
IDE windows. If you have split the Source Editor, only the partition
you maximize is displayed.
-
Clone a document.
Right-click the document tab in the Source Editor and choose Clone
Document. This enables you to have two partitions displaying the same
document.
-
Split the Source Editor.
Grabbing any document tab and drag it to the left or bottom margin of
the Source Editor. A red box shows you where the new Source Editor
partition will reside once you drop the document. Source Editor panes
can be split any number of times.
-
Move documents between Source Editor partitions.
Grab the document tab and drag it to the row of tabs in the destination partition.
Configuring the Editor
You can configure Source Editor settings in
the Options window by choosing either Editor or Fonts & Colors in
the left pane. Use the tabs to choose the editor settings you want to
modify. Some editor settings can be modified according to the file
type. In this section, we will focus on configuring the Java editor,
but many of the settings are the same for all editors.
Here is a quick overview of some of the more common customizations to the Source Editor:
-
View or change code templates.
To view or change code templates, select Editor in the left pane of the
Options window and then click the Code Templates tab. Choose an editor
by choosing a language from the drop-down menu. For example, to change
code templates used in the Java editor, choose Java from the drop-down
menu. You can now add, remove or modify the abbreviations you can use
when editing Java files. To modify a code template abbreviation, select
the abbreviation and edit the text in the Expanded Text field.
-
View or change recorded macros.
Click the Macros tab to add, modify and remove macros. Enter the code for macro in the Macro Code area.
-
Change the indentation
used in your code. Click the Indentations tab to modify indentation properties.
-
Turn off code completion.
To turn off code completion, select Editor in the left pane of the
Options window and then click the General tab and unselect the checkbox
for the Auto Popup Completion Window property.
-
Modifying fonts and colors.
You can use the Options window to set the font size and color for code.
In the Options window, choose Fonts & Colors in the left pane and
click the Syntax tab. Select All Languages from the Language drop-down
menu, select Default as the element type, and modify the Font property
to change the font size for all text in the Source Editor. You can also
choose a specific language from the drop-down menu to limit your
modifications to that language and modify language-specific settings.
For example, you can select Java from the Language drop-down menu and
select a category to change the font and color of each type of Java
code, such as method names or strings.