7 Working with Java Code

This chapter describes how to take advantage of the NetBeans editing tools and search features that help you create and modify the code for your Java applications.

This chapter contains the following sections:

7.1 About Working with Java Code

Use the Java Source Editor to write or edit Java code. The Java Source Editor is a full-featured text editor that is integrated with the GUI Builder, the compiler, the debugger, and other parts of the IDE. It contains a set of features to enhance your coding experience. For example, you can navigate to specific areas in the source code using accelerator keys or menu commands in the Java Source Editor. You can find and replace regular expressions, Java objects such as methods and interfaces.

In addition, you can use code templates to facilitate coding commonly used sequences of reserved words and common code patterns.

7.2 Editing Java Code

The IDE's built-in Source Editor enables you to view, create, and edit your Java source code. Open the Source Editor window by double-clicking a node in the Projects window, Files window, or Navigator window. Alternatively, you can open the Source Editor by choosing File > New to create a new file.

Note:

If a file is open in the GUI Builder, click Source in the editor's toolbar to open the Source Editor.

The IDE has many features to simplify coding of Java files such as:

  • Code completion. After you press Ctrl+Space, a dialog box appears and offers possible ways of completing the expression you are typing.

  • Code templates. You can enter common code snippets by typing abbreviations for those snippets and then pressing Tab.

  • Editor hints. For some common coding mistakes, the Source Editor provides hints for adding the missing code and offers to add the code for you automatically. To display hints, choose Source > Fix Code (Alt+Enter).

  • Insert Code. You can generate getters, setters, properties, and so on. Right-click in the Source Editor and choose Insert Code (Alt+Insert) to get a list of items that you can generate.

  • BeanInfo Editor. You can generate a BeanInfo class for a bean class by right-clicking the bean class in the Project window and choosing BeanInfo Editor. You can then visually edit the BeanInfo class by clicking the Designer tab in the Source Editor.

  • Word match. After you type the beginning characters of a word used elsewhere in your code and then press Ctrl+K, the Source Editor generates the rest of the word.

  • GUI Builder. Visually design Java GUI applications.

  • Refactoring. Change the structure of your code without changing the functionality.

  • Navigation Shortcuts. Include keyboard shortcuts that enable you to navigate to a source file, declaration statement, or Javadoc documentation based on the location of the insertion point.

  • Code Folding. Enables you to hide sections of code, such as Javadoc comments and method bodies.

  • Pair Completion, Smart Enter, and Smart Semicolons. When you type a quotation mark, bracket, brace, or parenthesis, the Source Editor automatically inserts the closing character. The matching is "smart", so the closing characters are not duplicated if you type them yourself.

  • Macros. Record macros by choosing Edit > Start Recording Macro.

  • Import Management. The Ctrl+Shift+I keyboard shortcut helps you generate missing import statements for the file. See

You can find information about other Source Editor features in help topics that are specific to the type of application you are developing.

For information on working with GUI source code, see Section 11.2.11, "How to Modify GUI Source Code."

For information on working with code formatting in the editor, see Section 2.13.2, "How to Specify Editor Formatting Options."

7.2.1 How to Identify Java Source Files

The IDE uses various icons to identify different types of source files. The following table shows some of the high-level icons used in the Projects and Files windows to indicate Java files and objects. In general, you can find out what an icon represents by holding your cursor over the icon to display the node's tool tip.

Icon Description
Java source file icon Java source file. The following file types are represented by this icon:
  • Classes, Entity Classes, Interfaces, Exceptions

  • Beans, Filters, Listeners, Servlets

  • Tag Handlers, Service Locators

  • Applets, JApplets

Java main class icon Java main class file
JAR or WAR archive JAR file or WAR file
Java packages root icon Java packages root
Java package icon Java package
Private Java package icon Private Java package
Empty Java package Empty Java package
Library packages root icon Library packages root
Package library icon Package library
Generic information file icon Generic information file. This node icon can represent the following file types:
  • Java Enum files

  • Java Annotation Type files

  • Java Package Info files

  • Empty files

Swing GUI form object icon Swing GUI form object. This includes:
  • JPanel Forms

  • Bean Forms

Swing JInternational Frame form icon Swing JInternational Frame form object
Swing and AWT GUI form icon Swing and AWT GUI form object. This includes:
  • Frame Forms

  • JFrame Forms

Swing and AWT GUI dialog form icon Swing and AWT GUI dialog form object. This includes:
  • Dialog Forms

  • JDialog Forms

Swing GUI applet form icon Swing and AWT GUI applet form object. This includes:
  • Applet Forms

  • JApplet Forms

Persistence Unit file icon Persistence Unit file
Database Schema icon Database schema file
JUnit file icon JUnit file. This includes:
  • JUnit Tests

  • Tests for Existing Class

  • Test Suites


Badge icons can be affixed to other file icons to indicate a particular state of the object. The following table lists some of the badges used in the Projects (Ctrl+1) and Files (Ctrl+2) windows.

Icon Description
Needs compile badge The file needs to be compiled. Either the file has not been compiled or the source has changed since the last compilation.
Error badge The file cannot be parsed. The file might contain an unrecoverable syntactic error, or there might have been a problem reading the file.

7.3 Navigating in Java Code

NetBeans provides many editing features that you can use to improve your productivity. These include features for locating and moving to the source code for your projects' classes and interfaces and their members. NetBeans provides keyboard accelerators to step from member to member in a class definition in the Java Source Editor.

For Java files, you can see a list of constructors, methods, and fields. For some kinds of XML files, you can use the Navigator to view the structure of the file. The Navigator window works with standard XML documents, XML schema files, and Ant scripts.

Choose Window > Navigator (Ctrl+7) to open this window.

To display a source file in the Navigator window:

  • Select the file in the Source Editor, the Projects window, the Files window, or the Favorites window.

Once a file is displayed, you can use the Navigator window to focus on a specific nodes contained in the document. To do so, click on a given node in the Navigator window, and your cursor automatically relocates to the node's position in the document.

7.3.1 Browsing Java Files

When a Java file is selected, a drop-down list appears at the top of the Navigator window to enable you to choose between the following two views:

  • Members view that lists, alphabetically, the selected source file's members (constructors, methods, and fields).

  • Bean Patterns that lists of a class's bean properties and event listeners.

You can display the Javadoc documentation for a member by hovering the mouse over the member's node. Right-click a node in the Members view to choose the following commands:

  • Go to Source. Opens the class in the Source Editor and places the insertion point at the beginning of the constructor, method, or field that the node represents.

  • Sort by Name. Displays the members in alphabetical order.

  • Sort by Source. Displays the members in the order in which they appear in the code.

  • Filters. Opens a submenu that enables you to select some common filters for the types of members to display:

    • Show Inherited Members. Displays members that come from classes that the current class extends

    • Show Fields. Displays the class's fields.

    • Show Static Members. Displays static fields and methods.

    • Show Non Public Members. Displays members that do not provide public access.

You can also activate and disable filters using the buttons at the bottom of the Navigator window.

The icons in the following table represent elements and bean patterns within the Java hierarchy. These icons are visible from the Navigator window (Ctrl+7).

Icon Description
Java class icon Java class or inner class
Constructor category node icon Category node for constructors
Constructor icon Constructor with default access
Private constructor icon Private constructor
Public constructor icon Public constructor or nonstatic initializer
Protected constructor Constructor with protected access
Static initializer icon Static initializer
Method category icon Category node for methods
Nonstatic method icon Method with default access (nonstatic)
Private method Private method (nonstatic)
Public method Public method (nonstatic)
Protected method icon Method with protected access (nonstatic)
Static method icon Method with default access (static)
Private static method icon Private method (static)
Static public method icon Public method (static)
Static protected method icon Method with protected access (static)
Field icon Category node for fields
Nonstatic field icon Field with default access (nonstatic)
Nonstatic private field icon Private field (nonstatic)
Nonstatic public field icon Public field (nonstatic)
Nonstatic protected field icon Field with protected access (nonstatic)
Static field icon Field with default access (static)
Static private field icon Private field (static)
Static public field icon Public field (static)
Static protected field icon Field with protected access (static)

7.3.2 Browsing XML Files

For XML files, the Navigator view displays a tree of elements. Right-click an element node to choose the following options for the level of detail to have displayed:

  • Show Attributes. Displays the attributes of each element.

  • Show Content. Displays the text content of each element.

7.3.3 Browsing Ant Scripts

When an Ant build script is selected, a drop-down list appears at the top of the Navigator window to enable you to choose between the following two views:

  • Ant Targets. Displays an alphabetical list of build targets.

  • XML View. Displays a hierarchical tree view XML elements in the build script

Select the Ant Targets view and right-click a node and to choose one of the following commands:

  • Open. Opens the file in the Source Editor and places the insertion point at the beginning of the selected target's line.

  • Run Target. Runs the selected target.

  • Create Shortcut. Opens a wizard that enables you to create a menu item, a toolbar item, a keyboard shortcut, and custom code for running the target.

  • Properties. Displays properties for the target in a property sheet. These properties are not editable.

7.3.4 Browsing an XML File

When you select the XML View, right-click a node to choose one of the following options for the level of detail to have displayed:

  • Show Attributes. Displays the attributes of each element.

  • Show Content. Displays the text content of each element

7.3.5 How to Navigate Within Your Code

While working in NetBeans, you can navigate within your source code and browse source and Javadoc documentations.

To go to the Java source for the identifier the insertion point is on:

  • Press Alt+O.

    Alternatively, you can choose Navigate > Go to Source. The class is opened in the Source Editor and the insertion point is placed at the beginning of the constructor, method, or field that the node represents.

To go to a Java file, JSP file, or tag file using hyperlinks:

Hold down the Ctrl key and move your over one of the following identifiers and click on it:

  • Java identifier (package, class, method, or variable)

  • JSP identifier (include directive, <jsp:include> element, <jsp:forward> element, or tag file reference).

To jump to the declaration for the Java method or field the insertion point is on:

  • Press Alt+G.

    Alternatively, right-click and choose Go To > Declaration from the context menu.

To go directly to a Java class:

  • Press Alt+Shift+O.

    Alternatively, you can choose Navigate > Go To Class.

To display Javadoc documentation for the entity that the insertion point is on:

  • Press Alt+F.

    Alternatively, right-click and choose Show Javadoc from the context menu.

    Note that to locate the documentation, the appropriate Javadoc library must be included in the Library manager.

To display Javadoc documentation for the method that corresponds to the method signature that you are using in your code:

  1. Place the insertion point between the closing parenthesis of the method call and the semicolon.

  2. Press Alt+F1.

    Alternatively, right-click and choose Show Javadoc from the context menu.

    If the insertion point is elsewhere in the line when you press Alt+F1, the documentation for the method with no parameters is displayed.

To go to a specific method or field in the currently displayed Java class:

  • Double-click the method or field in the Navigator window.

To switch Source Editor tabs:

  • Press Alt+Right or Alt+Left.

To jump back and forth among areas of code in which you have been working:

  • Use the Alt+K and Alt+L jump list keyboard shortcuts.

To bookmark a line of code:

  • Click anywhere in the line that you want to bookmark and press Ctrl+Shift+M.

    Press Ctrl+Shift+Period or Comma to cycle forward or backwards, respectively, through your bookmarks.

    Press Ctrl+Shift+M on a bookmarked line to remove the bookmark.

To go to a specific line number:

  • Press Ctrl+G.

To select the Projects window node for the current file in the Source Editor:

  • Press Ctrl+Shift+1.

7.4 Finding and Replacing Text

From the source editor, you can search for and replace text and expressions in your Java source code quickly and efficiently.

7.4.1 How to Find and Replace Text

You can search for text with the option of replacing it across your source file.

To search a source file currently open in the source editor, with the option to replace text:

  1. In the Source Editor, press Ctrl+F to display the Search panel, at the bottom of the editor, or Ctrl+H to display the Replace dialog box.

  2. Type the text to find and replace in the appropriate text fields.

    Use the Find combo box or the Replace combo box to select from recent entries. You can open the combo box with the Alt+down arrow and close it with the Alt+up arrow.

  3. Use any combination of the following options:

    • Match Case. Limits the search to text that has the same capitalization.

    • Whole Words. Matches the search text only to whole words in the file. Does not match words that contain but do not exactly equal the search text. Text separated by periods (for example, javax.swing.jPanel) is considered to be separate whole words. For example, if the search word is add and the Match Whole Words Only option is not selected, jPanel.add and blueSlider.addChangeListener both contain matches. If Match Whole Words Only is selected, only jPanel.add contains a match.

    • Regular Expressions. Enables you to search for and replace patterns based on regular expression constructs. For more information, see Section 7.5, "Using Regular Expressions."

    • Wrap Around. Continues the search from the beginning of the file when the end is reached.

    • Search Selection. Limits the search to the selected block of text.

    • Search Backwards. Searches back to the top of the file.

    • Wrap Around. Continues the search from the beginning of the file when the end is reached.

    • Highlight Results. Highlights all occurrences of the search text in the file. To unhighlight the text, do another search on the same text without this option selected, or press Alt+Shift+H in the Source Editor. Alt+Shift+H toggles between highlighting and unhighlighting the text.

    • Incremental Search. Tries to find the text as you type it (instead of waiting until you click the Find button).

  4. After the using the Find operation or Replace operation, use these keyboard shortcuts in the Source Editor:

    Shortcut Action
    F3 Finds the next occurrence of the search text.
    Shift+F3 Finds the previous occurrence of the search text.
    Alt+Shift+H Switches the highlight function on or off.
    Ctrl+F3 Searches for the word the insertion point is on, using the last settings specified in the Find dialog box.

For Java classes, use the Find Usages command to display usages of a class, method, or field throughout your source code. For information on the Find Usages command, see Section 8.11.2, "How to Find Class, Methods, and Field Usages."

7.5 Using Regular Expressions

You can use regular expressions to add flexibility to searches in the IDE. Regular expressions are composed of a special syntax that enables you to express a wide range of search patterns.

In the Find in Projects dialog box, you can use regular expressions to match file names or file text. In the Find dialog box and the Replace dialog box, you can use regular expressions to help you perform search and replace operations.

7.5.1 Regular Expression Constructs

Table 7-1 describes some of the special characters in regular expressions:

Table 7-1 Regular Expression Constructs

Construct Description

|

Or.

^

Matches text beginning with the subsequent characters.

$

Matches text ending with the preceding characters.

\

Escape character. Necessary if you want to match to a period (.), bracket ([), brace (() or other special character.

\n

New-line character.

\r

Carriage-return character.

[]

Used to delimit a set of characters.

*

Zero or more occurrences of the previous character or set of characters.

+

One or more occurrences of the previous character or set of characters.

.*

Wildcard.


For a more complete list of regular expression constructs and further discussion of regular expressions, see http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#sum.

7.5.1.1 Sample Regular Expressions

Table 7-2 lists some examples of regular expressions that you might use in file searches:

Table 7-2 Regular Expressions

Regular Expression Matches

"[^"\r\n]*"

Matches (quoted) strings in the document.

\{[^\{\}]*\}

Inner block of code between braces ({}). Blocks with nested braces are not matched.

[ \t]+$

All white space at the end of lines.


When using regular expressions in the Replace dialog box, you can use scalers in the Replace With field to refer to groups (constructs within parentheses) in the Find What field. $1 is the scaler assigned to the first group, $2 is assigned to the second group, and so on.

For information on finding classes, methods, and fields, see Section 8.11.2, "How to Find Class, Methods, and Field Usages."

For information on finding and replacing text, see Section 7.4.1, "How to Find and Replace Text."

7.6 Using Special Code Templates

Use code templates to speed up the entry of commonly used sequences of reserved words and common code patterns. For example, if you enter forc and press the Tab key, it expands into the following:

  for (Iterator it = col.iterator(); it.hasNext();) {
            Object object = it.next();

When you create code templates, there are several constructs that you can use to customize the way the code template behaves. You can look at the default IDE code templates in the Options window, under the Tools menu, for examples from which you can learn.

In general, a code template parameter can be specified by its name and a set of optional hints. Hints serve as guidance when computing the values assigned by the infrastructure to the parameters on template expansion. Syntax for parameter definition is as follows:

${param_name hint=value hint=value ...}

However, boolean hints that can be written without the value part:

${param_name hint} translates to ${param_name hint=true}

Some parameter names are reserved by the code template infrastructure:

  • ${cursor} defines the position where the caret will be located after the editing of the code template values finishes.

  • ${selection} defines the position for pasting the content of the editor selection, which is used by the 'selection templates' that appear as hints whenever the user selects text in the editor.

Similarly, some of the hint names are reserved by the code template infrastructure:

  • ${param_name default="value"} defines the parameter's default value.

  • ${param_name editable=false} can be used to disable user's editing of the parameter.

  • ${param_name instanceof="java.util.Collection"} requires the parameter value to be an instance of the given type.

  • ${param_name array} requires the parameter value to be of an array type (including arrays of primitive data types).

  • ${param_name iterable} requires the parameter value to be of an array type or an instance of "java.lang.Iterable". Can be used in 'for-each' cycles.

  • ${param type="java.util.Iterator"} requires the parameter value to be the given type. The infrastructure tries to use short name Iterator and import java.util.Iterator if possible.

  • ${param_name iterableElementType} requires the parameter value to be the type of the iterable element. Can be used in 'for-each' cycles.

  • ${param_name leftSideType} requires the parameter value to be the type of the expression on the assignment's left side.

  • ${param_name rightSideType} requires the parameter value to be the type of the expression on the assignment's right side.

  • ${param_name cast} defines that the parameter value would be a type cast if necessary.

  • ${param_name newVarName} defines that the parameter value should be a 'fresh' unused variable name in the given context.

7.7 Using Java Editor Shortcuts

Table 7-3 lists the keyboard shortcuts you can use to perform the following Java Source Editor operations:

Table 7-3 Java Editor Keyboard Shortcuts

Keys Action

Ctrl+Shift+B

Goes to the source of the item the insertion point is on.

Ctrl+B

Goes to the method or variable declaration for method or variable the insertion point is on.

Ctrl+Q

Goes to the line in the file where the last change took place.

Ctrl+/

Comments/uncomments the current line or selected lines.

Alt+Shift+F

Formats the selected code or the entire file if nothing is selected.

Alt+Shift+Left

Moves the selected line or lines one tab to the left.

Alt+Shift+Right

Moves the selected line or lines one tab to the right.

Alt+Shift+Up

Moves the selected line or lines one line up.

Alt+Shift+Down

Moves the selected line or lines one line down.

Ctrl+Shift+Up

Copies the selected line or lines one line up.

Ctrl+Shift+Down

Copies the selected line or lines one line down.

Ctrl+Slash

Toggles the commenting out of the current line or selected lines.

Ctrl+Space

Shows code completion box.

Alt+Insert

Pops up a context aware menu that you can use to generate common structures such as constructors, getters, and setters

Alt+Enter

Displays editor hints. The IDE informs you when a hint is available when the light bulb is displayed.

Ctrl+Shift+I

Generates the import statements required by all classes specified in the file.

Alt+Shift+I

Generates the import statements required by the class under the cursor.

Ctrl+P

Selects the next parameter. You must have a parameter selected (highlighted) for this shortcut to work.

Ctrl+Shift+Space

Shows documentation for item under the cursor.

Ctrl+Shift+K

Generates the next word used elsewhere in your code as you type its beginning characters.

Ctrl+K

Generates the previous word used elsewhere in your code as you type its beginning characters.

Ctrl+R

In place rename.