corner imagecorner image
FeaturesPluginsDocs & SupportCommunityPartners

NetBeans IDE 5.0 Hacks (Part 1)

A collection of the best tech tips from NetBeans blogs
Use a Single Editor Well - The editor should be an extension of your hand;
make sure your editor is configurable, extensible, and programmable.


-- The Pragmatic Programmer


See also NetBeans IDE Hacks table of contents


Editor Hacks Navigation Hacks


Editor Hacks


Refactor Your Code

source 1, source 2

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 orginal source.

  • Rename - Finds every usage of the name of a class, variable, or method, and updates all source code in your project to reflect the name change.
  • Safely Delete - Checks for references to a code element and only deletes it if no other code references it.
  • Move Class - Moves a class to another package or into another class.
  • Pull up - Pulls the selected method to the parent class of current class.
  • Push down - Pushes down the selected method to the class subclassing current class.
  • Move Inner to Outer Level - Moves an inner class one level up in hierarchy.
  • Convert Anonymous Class to Inner - Converts an anonymous class to an inner class that contains a name and constructor. The anonymous inner class is automatically replaced with a call to the new inner class.
  • Introduce variable - Introduces a new local variable to simplify a complex expression.
  • Encapsulate Fields - Creates getter and setter methods for a field (instance variable) and optionally updates all referencing code to access the field using the getter and setter methods.
  • Extract method - Creates a method from selected lines of code and replaces them by a call to the method.
  • Extract Interface - Creates a new interface from the selected public non-static methods in a class or interface.
  • Extract Superclass - Creates a new abstract class, changes the current class to extend the new class, and moves the selected methods and fields to the new class.
  • Change Method Parameters - Adds parameters to a method and changes the access modifier.
  • Use Supertype Where Possible - Changes code that references the selected class (or other type) to instead use a supertype of that type.

You should 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 selecting Clean and Build Project from the menu.


Auto-Generate Getters and Setters

source 1 source 2, source 3

Despite our best planning, it happens that we need to change data types we use in classes: The field that was an int before, is now an int array. Luckily, you did not expose the field publicly — it would have taken you a while to hunt down and update all the broken classes that would have accessed this field directly. Instead, you encapsulated the field:

Encapsulating a field simply means accessing it only via getter and setter methods. If a data type changes, you often get away with just updating some getters and setters, which saves you a lot of time and nerves. Either right-click in the editor, or go to the main menu to see how the IDE's Refactoring commands can quickly encapsulate your fields by creating getter and setter methods.

  • Select Refactor > Encapsulate Fields from the menu. A dialog pops up and lists all fields in the class for which you can create getters and setters. Use this method to create getters and setters for several fields in one go.

  • Alternatively, position the cursor between classes, and hit the keyboard combination Ctrl-Space to invoke the Code Completion window. Choose a field to encapsulate, and hit return. Use this method if you just quickly need to create one getter, or one setter.

  • There is also a third, very intuitive method: Again, position the cursor between classes. Start typing the name of a getter or setter to generate, for instance getName. Then hit Ctrl-Space. The Code Completion window pops up and suggests to "Create getter getName for field name". Hit return to generate the method.

Another nice little timesaver when modifying existing getters and setters are the prepend shortcuts. With these shortcuts, you can for instance quicky turn public int size() into public int getSize(). Place the cursor before a method identifier, e.g. before |size().

  • Press Alt-U and then S to prepend the word set.
  • Press Alt-U and then G to prepend the word get.
  • Press Alt-U and then I to prepend the word is (for getters that return booleans).
Note this is a multi-key shortcut.


Fix Import Statements

source

Often when you copy a code snippet into your sources, the snippet does not contain import statements and the code does not compile. In these cases, the Editor shows a red warning box next to the line of code. If you move the mouse over the box, a hint explains that one of the symbols could not be found.

When you are certain the symbols exist in your path (and the error is not due, say, a typo) press Alt-Shift-F to have the IDE fix the missing import statements automatically. You can also call this function by right-clicking in the Editor and selecting Fix Import Statements.


Abbreviate Common Code Snippets

source 1, source 2

Abbreviations save you a lot of time: Instead of repetitively typing the same common and tedious code fragments, you type only a few letters and then immediately hit the spacebar. The IDE replaces the mnemonic by the full code template.

  • Typing fori and space completes to...
    for (int i = 0; i < args.length; i++) {
         |
    }
    Alternatively, you can type for and then press Ctrl-Space.

  • Typing sout and space completes to...

    System.out.println(""); 

  • psfs and space completes to...

    private static final String

You can check out the list of available code templates by selecting Tools > Options > Editor > Code Templates from the menu. In this preference panel, you can also define your own abbreviations for any code you commonly use. Here's a list of special identifiers you can use in the templates.


Implement Abstract Methods Fast

source

The IDE can help you if your code does not compile. For instance, when you need to implement abstract methods in a class that extends another class. As long as you have not implemented all methods required for the class to compile, a red warning box will appear next to the class declaration.

Position the cursor into the declaration, and a lightbulb symbol will appear. Clicking the lighbulb always displays a hint how to fix the class. In our example the hint would suggest to "Implement all abstract methods."

To make the IDE execute the hint, either click it, or press Alt-Return. The IDE generates skeletons of all necessary abstract methods, or whatever it was the hint contained.

See also "Override Any Method Fast".


Override Methods Fast

source

  1. Type the names of methods to override -- e.g. toString. Then hit Ctrl-I.
  2. The Override Method dialog appears: Select the method(s) to override. If you want to override abstract methods, check "Show Abstract Methods Only." Check the boxes if you want the IDE to create the methods including a super call, or copy Javadoc comments. Press OK.
  3. The IDE generates the method skeleton for you.

See also "Implement Abstract Methods Fast"


Find out Expected Method Parameters

source

Want to know the arguments to a method call? Then press Alt-P while writing the call. This shows a quick cheat-sheet of expected arguments for the method you are writing.


Catch Exceptions Quickly

source

Often you need to surround a method with a try-catch statement because it can throw an exception that should be caught.

import java.io.File;

public class CoffeeMachine {
  public CoffeeMachine() {
     File f = File.createTempFile("coffee", "tmp");
  }
}
In this example, you would right-click the line containing the call to createTempFile() and execute the Surround With Try-Catch action from the Editor's context menu. The keyboard shortcut for this action is Alt-Shift-W. This will result in the following code:
import java.io.File;
import java.io.IOException;

public class CoffeeMachine {
  public CoffeeMachine() {
     try {
        File f = File.createTempFile("coffee", "tmp");
     } catch (IOException e) {
        |
     }
  }
}

The line which performs a dangerous IO operation was surrounded by a try-catch block. Notice that the correct import was added into the list of imports as well. The cursor gets placed in the catch block: Now it's time for you to write code how to respond to the exception being thrown.


Compare Two Files

source

NetBeans has a built-in file comparison function, diff, to highlight differences between two files. Most people know the Diff View from the IDE's versioning support. But did you know that you can diff files even if they are not version controled?

  1. In the Projects view, click with the ctrl key presed to select two files.
  2. Right-click one of the selected files, and select Tools > Diff from the context menu.
  3. The graphical Diff view appears and lets you step through all differences.

Note that Diff only appears in the Tools menu when two files are selected and in focus.


Graphical diff in NetBeans


Out-Smart Search & Replace

source 1, source 2, source 3

The Search & Replace command (Ctrl-H) supports searching for regular expressions: For instance searching for the escape sequence of two newline characters "\n\n" will find all lines that are followed by an empty line. Unfortunately, the Replace With field doesn't support escape sequences yet. So what to do if you want to replace two newline characters by one?

Despite not yet interpreting escape sequences, the Replace With field already supports back-references. This means you can use a back-reference to smuggle the newline character "\n" into the Replace With field:

Using this neat trick, you can easily replace two newlines by one. Of course, this does not only apply to newlines, but to any regular expression. Some examples for symbols most commonly used in regular expressions are

  • \n, the a newline character,
  • \w, any alphanumeric character,
  • \t, the tab character.

Regular expressions in combination with back-references are extremely powerful tools when replacing text. Intrigued? This is how they work: Basically, each substring that is surrounded by brackets in the search term is 'copied', and can be 'pasted' into the replace term. You paste the first bracketed substring into the replace term by writing $1, the second one by writing $2, and so on.

For example, you have a long row of variable declarations:

...
public int x;
public int y;
public int z;
But then you decide you want them all to be private and initialized to zero:
...
private int x = 0;
private int y = 0;
private int z = 0;

Obviously, you cannot use basic Replace due to the unique variable names. Variable names are composed of one or more alphanumeric characters; and as a regular expression, a sequence of alphanumeric characters is expressed as \w+. Knowing this, you can capture the variable names from the search term with the bracketed (\w+) symbol, and restore them in the replace term by calling the back-reference $1 symbol.

Find What:    public int (\w+);
Replace With: private int $1 = 0;

Remember you can use $2, $3, etc, for the following substrings if you reference several bracketed expressions at once.

The symbol $0 stands for the whole search term. For instance this is useful to close each <img ... > tag in an HTML file by replacing it with <img ... />. In regular expressions, the [^] symbol is used for negation, therefor [^>]+ matches a string of any characters but a closing bracket.

Find What:    <img [^>]+
Replace With: $0 /

Learn about this powerful tool in Jan Goyvaerts's Regular Expression Quick Start. This nifty editor feature saves you a lot of time you would spend with manual editing — And you'll impress people with your coding speed as well.


Switch From Uppercase to Lowercase

source 1, source 2

Did you know that NetBeans IDE can convert text to UPPER CASE or lower case?

Select the String, then

  • press Alt-U and then U for all uppercase
  • press Alt-U and then L for all lowercase
  • press Alt-U and then R to invert a word's case, that is, turn upper to lower case, or lower to upper.
Note this is a multi-key shortcut.


Navigation Hacks


Select Chunks of Code Fast

source

NetBeans supports Smart Selection, a very popular IDE feature. Use Smart selection to select whole chunks of code with only one keystroke: The first keystroke selects the expression, the second the statement, the third the whole block, the fourth the method, and the fifth the whole class. This is how you use it:

  1. Position the cursor on a line inside a method.
  2. Press Alt-Shift-S to select the next bigger chunk, ...
  3. ... and Alt-Shift-A to select the next smaller chunk.

Try it! Smart Selection is extremely useful when copying and pasting code.


Open a Class in the Editor Fast

source

How often do you go to the Project view, scroll down and search for a file inside the project, and then double-click it to open it in editor? Doing this is probably fine when you work on small projects. But as the project grows, the tree hierarchy to scroll through grows bigger, too. And what if you do not remember in which package the class is that you want to edit?

Instead of browsing huge project trees manually to find a class, open the file directly by invoking the Go To Class dialog (Alt-Shift-O). Just type in the first letters of the class's name until it is unique. Press enter and the file opens in the Editor.


Click on screenshot for a demo.


Jump to Methods and Fields Fast

source 1, source 2

Instead of scrolling up and down in the Editor window with the mouse, you can navigate very fast to a method or field in the source editor:

  • Press Ctrl-7 to give focus to the Navigator.
  • Type in the first couple of unique letters of the method, e.g. "ma" for main. You can also use the up and down arrow keys to select the next or previous item.
  • Press enter. The file opens if necessary, and the cursor is positioned directly at the method or field you selected.

Note that the Navigator contains both a Members view and an Inheritance view of your class. If you hover over Navigator items with the mouse, it will present you with a quick peek at their APIs by showing the Javadoc.


Jump to a Method's Definition — and Back Again

source 1, source 2

You are staring at a method call or variable in a class, and cannot for the life of you remember were you originally defined the thing. Wouldn't it be great if you could directly jump to the definition, make a quick fix, and jump back again? You can!

Hover your mouse over the sources in the Editor and hold down the ctrl key. The text color of the element under the mouse changes to blue and it becomes underlined, just like a hypertext link in a web browser. With a single left click, you directly jump to the source where this element was defined. If the cursor is positioned within the element, the keyboard shortcut Alt-G will equally take you to the definition.

Now you want to get back to your original source location — Did you ever notice that little yellow arrow in the editor bar? Click on it and it will take you back to every previous cursor position in the source code! The keyboard shortcut Alt-K will equally take you back.

Both the Back button and the Alt-K shortcut jump back to the previous cursor position, even if you did not use a hypertext link to jump there.


Switch Tabs in the Editor

source

A good programmer breaks a project down into several classes with independent tasks, right? But what does a good programmer do when he has so many files open that they no longer fit the screen — scroll? Nope: He switches tabs. This is how you do it:

  1. Call up the list of all open tabs in the Editor by by pressing Ctrl-Tab while keeping the ctrl key pressed.
  2. Still with the ctrl key pressed, browse through the list of open tabs by hitting Ctrl-Tab; browse backwards through the list with Shift-Ctrl-Tab. Releasing the keys switches to the selected tab.
  3. Pressing Ctrl-Tab once and then letting both keys go immediately, will switch directly back to the previous tab used.

Note however, that in some operating systems, Ctrl-Tab is already associated with another conflicting action. In this case, use Ctrl-~ instead. (Thanks to Jesse Glick for this tip.)


Select A File's Node Fast

source

You have a file open in the Editor, how do you quickly find out to which project it belongs? Easy, you say: You point at the file's tab, and the tooltip that pops up shows the file path.

But you want to call a context-sensitive command on the file node in the Projects View. Obviously, you don't want to drill down the whole path manually, double-clicking all the intermediate nodes. Isn't there an easier way? There is.

  • To quickly open and select the currently opened file's node in Projects view, press Shift-Ctrl-1.
  • Similarly, to select the filenode in Files view, press Ctrl-Shift-2.
  • To open the file in Favorites view, press Ctrl-Shift-3.

Note that these commands are only meaningful if the file's source root is already open in the Explorer.

Bookmark this page

del.icio.us furl simpy slashdot technorati digg

My favorite NetBeans Hack

This collection of NetBeans hacks is a community effort -- this means you can help us collect more NetBeans tips & tricks. Send your favorite hack in and we'll include it! (We reserve the right to edit, republish, or not use your hacks.)

Companion
Projects:
MySQL Database Server   GlassFish Community: an Open Source Application Server   Open Solaris  Open JDK: an Open SourceJDK   Mobile & Embedded Community     Sponsored by 
Sponsored by Sun Microsystems