Book Image

Java EE 7 Development with NetBeans 8

By : David R Heffelfinger
5 (1)
Book Image

Java EE 7 Development with NetBeans 8

5 (1)
By: David R Heffelfinger

Overview of this book

Table of Contents (18 chapters)
Java EE 7 Development with NetBeans 8
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

NetBeans tips for effective development


NetBeans offers a wide array of features that make Java and Java EE development easier and faster. In the following few sections, we cover some of the most useful features.

Code completion

The NetBeans code editor includes a very good code completion feature, for example, if we wish to create a private variable, we don't need to type the whole private word, we can simply write the first three letters (pri), then hit Ctrl + Space and NetBeans will complete the word private for us.

Code completion also works for variable types and method return values, for example, if we want to declare a variable of type java.util.List, we simply need to type the first few characters of the type, then hit Ctrl + Space NetBeans will try to complete with variable types in any of the packages we have imported in our class. In order to make NetBeans attempt to complete with any type in the classpath, we need to hit Ctrl + Space again.

As we can see in the preceding screenshot, NetBeans displays JavaDoc for the class we selected from the code completion options. Another time-saving feature is that the class we selected from the options is automatically imported into our code.

Once we have the type of our variable, we can hit Ctrl + Space right after the variable and NetBeans will suggest variable names.

When we want to initialize our variable to a new value, we can simply hit Ctrl + Space again and a list of valid types is shown as options for code completions as demonstrated in the following screenshot:

In our example, our type (java.util.List) is an interface, therefore, all classes implementing this interface are shown as possible candidates for code completion. Had our type been a class, both our class and all of its subclasses would have been shown as code completion candidates.

When we are ready to use our variable, we can simply type the first few characters of the variable name, then hit Ctrl + Space.

When we wish to invoke a method in our object, we simply type a period at the end of the variable name, and all available methods are displayed as code completion options.

Notice how the JavaDoc for the selected method is automatically displayed.

Code templates

Code templates are abbreviations for frequently used code snippets. To use a code template, we simply type it into the editor and hit the Tab key to expand the abbreviations into the full code snippet it represents.

For example, typing sout and pressing the Tab key will expand into System.out.println("");, with the caret placed between the two double quotes.

Some of the most useful code templates are listed in the following table, please note that code templates are case sensitive.

Abbreviation

Example expanded text

Description

Psf

public static final

Useful when declaring public, static, and final variables.

fore

for (Object object : list) {

}

Use the enhanced for loop to iterate through a collection.

ifelse

if (boolVar) {

} else {
}

Generate an if-else conditional statement.

psvm

public static void main(String[] args) {

}

Generate a main method for our class.

soutv

System.out.println("boolVar = " +
        boolVar);

Generate a System.out.println() statement displaying the value of a variable.

trycatch

try {

} catch (Exception exception) {
}

Generate a try-catch block.

whileit

while (iterator.hasNext()) {
       Object object = iterator.next();

 }

Generate a while loop to iterate through an iterator.

To see the complete list of code templates, click on Tools | Options, click on the Editor icon, then on the Code Templates tab.

We can add our own templates by clicking on the New button. We will be prompted for the template's abbreviation. Once we enter it, our new template will be added to the template list and will automatically be selected. We can then enter the expanded text for our template in the Expanded Text tab.

Code templates can be used not only for Java but for HTML, CSS, and all other editors in NetBeans. To view/edit templates for other languages, simply select the desired language from the Language drop-down menu under the Code Templates tab as indicated in the following screenshot:

Keyboard shortcuts

NetBeans offers several keyboard shortcuts that allow very fast navigation between source files. Memorizing these keyboard shortcuts allows us to develop code a lot more effectively than relying on the mouse.

Note

Some of the most useful NetBeans' keyboard shortcuts are listed in this section, but this list is by no means exhaustive. The complete list of NetBeans' keyboard shortcuts can be obtained by clicking on Help | Keyboard Shortcuts Card.

One useful keyboard shortcut that allows us to quickly navigate within a large Java file is Ctrl + F12. This keyboard shortcut switches focus to the Navigator window, which displays an outline of the current Java file and shows all its methods and member variables.

When the Navigator window has focus, we can simply start typing to narrow down the list of member variables and methods shown. This keyboard shortcut makes it very fast to navigate through large files.

Hitting Alt + F12 will open the Hierarchy window, which outlines the class hierarchy of the current Java class.

We can use the previous shortcut to quickly navigate to a superclass or a subclass of the current class.

Another useful keyboard shortcut is Alt + Insert. This keyboard shortcut can be used to generate frequently used code such as that for constructors, getter and setter methods, among others.

The code will be generated at the current location of the caret.

Additionally, when the caret is right next to an opening or closing brace, hitting Ctrl + [ results in the caret being placed in the matching brace. This shortcut works for curly braces, parenthesis, and square brackets. Hitting Ctrl + Shift + [ has a similar effect, but this key combination not only places the caret in the matching brace, it also selects the code between the two carets:

Sometimes, we would like to know all the places in our project where a specific method is invoked. Hitting Alt + F7 while the method is highlighted allows us to easily find out this information.

The keyboard shortcuts works with variables as well.

NetBeans will indicate compilation errors in our code by underlining the erroneous line with a squiggly red line as shown in the following screenshot. Placing the caret over the offending code and hitting Alt + Enter will allow us to select from a series of suggestions to fix our code:

Sometimes navigating through all the files in a project can be a bit cumbersome, especially if we know the name of the file we want to open but we are not sure of its location. Luckily, NetBeans provides the Shift + Alt + O keyboard shortcut that allows us to quickly open any file in our project:

Additional useful keyboard shortcuts include Shift + Alt + F to quickly format our code, Ctrl + E (Cmd + E on Mac OS) to erase the current line, much faster than highlighting the line and hitting backspace. Sometimes we import a class into our code and later decide not to use it. Frequently, the lines where the class is used are deleted but we forget to delete the import line at the top of the source file. NetBeans will generate a warning about the unused import; hitting Ctrl + Shift + I will delete all unused imports in one fell swoop, plus it will attempt to add any missing imports.

One last thing worth mentioning, even though it is not strictly a keyboard shortcut, a very useful feature of the NetBeans editor is that left-clicking on a method or variable while pressing Ctrl will turn the method or variable into a hyperlink. Clicking on this hyperlink will result in NetBeans taking us to the method or variable declaration.

Understanding NetBeans visual cues

In addition to offering keyboard shortcuts, code templates, and code completion, NetBeans offers a number of visual cues that allow us to better understand our code at a glance. Some of the most useful cues are illustrated in the following screenshot:

When there is a warning in our code, NetBeans will alert us in two ways, it will underline the offending line with a squiggly yellow line, and it will place the following icon in the left margin of the offending line:

The light bulb in the icon indicates that NetBeans has a suggestion on how to fix the problem. Moving the caret to the offending line and hitting Alt + Enter, as discussed in the previous section, will result in NetBeans offering one or more ways of fixing the problem.

Similarly, when there is a compilation error, NetBeans will underline the offending line with a red squiggly line, and place the following icon on the left margin of said line.

Again, the light bulb indicates that NetBeans has suggestions on how to fix the problem. Hitting Alt + Enter in the offending line will allow us to see the suggestions that NetBeans has.

NetBeans not only provides visual cues for errors in our code, it also provides other cues, for example, placing the caret next to an opening or closing brace will highlight both the opening and closing brace, as shown in the populateList() method. This is demonstrated in the previous screenshot.

If one of our methods overrides a method from a parent class, the following icon will be placed in the left margin next to the method declaration:

The icon is an upper case "O" inside a circle, the O stands for "override".

Similarly, when one of our methods is an implementation of a method declared on an interface, the following icon will be placed in the left margin of the method declaration.

The icon is an uppercase "I" inside a green circle, which stands for "implements".

NetBeans also provides visual cues in the form of fonts and font colors, for example, static methods and variables are shown in italics, member variables are shown in green, and Java reserved keywords are shown in blue.

Another nice feature of the NetBeans editor is that highlighting a method or variable highlights it everywhere it is used in the currently open file.

Accelerated HTML5 development support

NetBeans has the capability to update deployed web pages in real time as we edit the markup for the page. This feature works both for HTML files and for JSF facelets pages (discussed in the next chapter).

In order for this feature to work, we need to use either the embedded WebKit browser included with NetBeans, or Google's Chrome browser with the NetBeans Connector plugin. To select the browser to run our web application, we need to click on the browser icon on the NetBeans toolbar, then select one of the options under With NetBeans Connector, as shown in the following screenshot:

The accelerated HTML5 development support feature works "out of the box" with the embedded WebKit browser. To test it, select the embedded WebKit browser, then run the application we deployed earlier in this chapter in the Deploying our first application section. It will run inside NetBeans when using the embedded WebKit browser.

To test the accelerated HTML5 development functionality, let's make a simple change to one of the pages on the application. Open the file called home.xhtml and look for a line containing the text Number.

<h:panelGrid border="1" columns="5" style="font-size: 18px;">
  Number: 
    <h:inputText id="inputGuess" value="#{game.guess}"
      required="true" size="3" 
      disabled="#{game.number eq game.guess}" 
      validator="#{game.validateNumberRange}">
    </h:inputText>
    <h:commandButton id="GuessButton" value="Guess"
      action="#{game.check}" 
      disabled="#{game.number eq game.guess}"/>
    <h:commandButton id="RestartButton" value="Reset"
      action="#{game.reset}" immediate="true" />
      <h:outputText id="Higher" value="Higher!"
        rendered="#{game.number gt game.guess and
          game.guess ne 0}" 
        style="color: red"/>
      <h:outputText id="Lower" value="Lower!" 
        rendered="#{game.number lt game.guess and game.guess ne 0}" 
        style="color: red"/>
      </h:panelGrid>

Replace the string Number with the string Your Guess, so that the markup now looks like this:

<h:panelGrid border="1" columns="5" style="font-size: 18px;">
  Your Guess: 
    <h:inputText id="inputGuess" value="#{game.guess}"
      required="true" size="3" 
      disabled="#{game.number eq game.guess}" 
      validator="#{game.validateNumberRange}">
    </h:inputText>
    <h:commandButton id="GuessButton" value="Guess"
       action="#{game.check}" 
       disabled="#{game.number eq game.guess}"/>
    <h:commandButton id="RestartButton" value="Reset"
      action="#{game.reset}" immediate="true" />
    <h:outputText id="Higher" value="Higher!"
      rendered="#{game.number gt game.guess and
        game.guess ne 0}" style="color: red"/>
    <h:outputText id="Lower" value="Lower!"
      rendered="#{game.number lt game.guess and 
        game.guess ne 0}" style="color: red"/>
    </h:panelGrid>

Save the file, and without redeploying the application or reloading the page, go back to the embedded browser window. Our change will be reflected on the rendered page.

In order for the accelerated HTML5 development feature to work in Chrome, we need to install the NetBeans Connector plugin from the Chrome Web Store. If we select Chrome as our web browser (under the With NetBeans Connector section on the menu) and attempt to run our application, NetBeans will prompt us to install the plugin.

Clicking on the button labeled Go to Chrome Web Store takes us directly to the download page for the NetBeans Connector plugin:

Clicking on the button labeled Free at the upper-right corner results in a pop-up window displaying the permissions for the NetBeans connector plugin:

Clicking on the Add button automatically installs the plugin. We can then run our project on the Chrome browser and any changes we make to the markup will be instantly reflected on the browser.

As we can see in this screenshot, when running our application through the NetBeans connector, Chrome displays a message alerting us of the fact.