Content
Using an Integrated Development Environment (IDE) for developing applications saves you time by managing windows, settings, and data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-drop features make creating graphical user interface (GUI) components or accessing databases easy, and highlighted code and debugging features alert you to errors in your code. The NetBeans IDE is open source and is written in the Java programming language. It provides the services common to creating desktop applications -- such as window and menu management, settings storage -- and is also the first IDE to fully support JDK 5.0 features. The NetBeans platform and IDE are free for commercial and noncommercial use, and they are supported by Sun Microsystems. This tutorial is aimed at those who are new to using IDEs, fairly new to programming, and new to the Java platform. You'll learn to create a simple desktop application with a GUI interface and functionality that calculates overtime pay using basic features of the NetBeans IDE. This tutorial provides explanations for the code where appropriate, as well as links to the Java API and information about objects as they are introduced. Though the NetBeans environment also provides many rich features for the various Java platforms, such as Java Platform, Enterprise Edition (Java EE) and Java Platform, Micro Edition (Java ME), this article covers only Java Platform, Standard Edition (Java SE) technology, which is generally the entry point for new developers and programmers. Future tutorials will discuss more advanced features. To follow this tutorial, you need to have downloaded and installed the JDK and the NetBeans IDE. Or you can download JDK 5.0 and NetBeans 4.1 separately to ensure that you have the latest versions. Because the NetBeans IDE is open source and in continual improvement, you may notice slight differences between the screen captures in this article and the latest download. This tutorial is based on NetBeans 4.1 and may vary slightly from later versions as they become available. The NetBeans IDE has many features and tools for each of the Java platforms. Those in the following list are not limited to the Java SE platform but are useful for building, debugging, and deploying applications and applets: Source Code Editor
GUI Builder
Database Support
The NetBeans IDE also provides full-featured refactoring tools, which allow you to rename and move classes, fields, and methods, as well as change method parameters. In addition, you get a debugger and an Ant-based project system. To get started, download the latest stable version from the NetBeans.org web site and install it on whatever platform you use for programming and development. The NetBeans.org web site lists the computer requirements needed to run the IDE. NetBeans can automatically upgrade its core and extension modules over the Internet, and it has a module that runs periodically on your behalf to check for updates to the version of NetBeans you're using. In addition, the Update Center can update and install any modules you okay or request.When you start the application, you should get a welcome screen similar to Figure 1.
You'll notice that this welcome screen makes getting started right away an easy process by displaying a Quick Start Guide up front, as well as the options to begin a project or open one. In addition, you can select the Sample Project for a quick example of how code is set up in this IDE. NetBeans is fairly intuitive to use, especially if you've used IDE software in the past. You'll get familiar with three concepts right away: projects, nodes, and workspaces. Within NetBeans, you work within the context of a project, which consists of an organized group of source files and associated metadata; project-specific properties files; an Ant build script and run settings; and all the tools you'll need to write, compile, test, and debug your application. You can create a main project with subprojects, and you can link projects through dependencies. So getting started is as easy as giving your project a name. Once you tell NetBeans the name of a new project, it then
Click File from the main menu and select New Project. The New Project wizard pops up and looks similar to Figure 2.
From there, you select a Category from General, Web, Enterprise, Samples. Notice that General creates a project containing an empty application. Choose General and select Java Application. Next, name the project and select a location within your file system. Note that the IDE automatically creates a main class for your application if you want it to. Click Finish. The Project window displays only the files that are likely to be regularly edited, such as source files and tests. To see more details about your project, click on the Files tab. Here, if you click on the project folder you created, you'll see that the folder contains the Ant script and properties files that control how your project is built and run:
The project folder also contains the output folder for compiled classes, JAR files (for Java SE projects) or WAR files (for web projects), and Javadoc.
NetBeans allows you to see all your objects in a project represented as nodes of a tree, each having its own icon to represent the type of object the node represents. Within the Files tab, you can easily view the trees and representative nodes. If you double-click on a node, it opens up into a subtree that contains more detail. You can collapse or expand trees as necessary. Right-clicking on any node provides easy access to specific functions that you can perform and tools that you can use on that object. Expand the subtrees of the project node that you just created, and you will notice that the fields, constructors, methods, and bean patterns appear as node branches. The Runtime tab shows you a view of what has happened when you tried to run your application. The Runtime view lists various facilities available to your project. In addition, you can see what operations have been performed and troubleshoot some types of runtime errors, such as when a remote method invocation (RMI) connection is causing a problem. You'll get more familiar with this view after you have written, compiled, debugged, and run your applications. Return to the Files tab. Double-clicking a source file automatically opens the file in the workspace to the right, bringing up the appropriate Source Editor. Notice the file system that has been created. Files and directories associated with an application project are organized in a logical fashion. Double-click the
When your application is organized into several projects, the main project serves as the entry point to the application. Usually, the main project contains the main class that starts the application. To make a project the main project, right-click the project's node in the Projects window and choose Set Main Project. You can click right into the Source Editor and write code. When you write code this way, you'll notice that the editor automatically highlights code in color as appropriate and completes your code. You can customize colors in the highlighting by going to Tools -> Options -> Editing -> Editor Settings -> Java Editor -> Fonts and Colors. Code completion finishes package names, classes, interfaces, and common methods. As handy as code completion can be, you may sometimes not want it. You can easily turn off this feature by pressing Esc. Or you can turn it off more permanently by going to Tools -> Options -> Editing -> Editor Settings -> Java Editor and deselecting the Code Completion Instant Substitution checkmark. You can also save time by assigning abbreviations that the Source Editor expands for you. Type the first few letters of an abbreviation and press the spacebar. The Source Editor then expands the abbreviation.
Turn on line numbering easily through the View menu.
The NetBeans IDE also provides forms, templates, and wizards that make creating code easy. In the Projects window, you can also add to your source code by right-clicking the fields, methods, and bean patterns on the nodes. By selecting Add on the menu that appears, you get forms similar to Figures 5 and 6.
You can use two project templates to import your existing source code:
The following steps cover use of the first template to create a standard Java project without the use of existing Ant scripts.
Your project will now be displayed in the Projects and Files windows. Now that you're familiar with the nuts and bolts of the NetBeans IDE, the next sections will step you through creating, compiling, debugging, and running an application that uses a simple GUI interface with some background functionality that calculates the rate of regular and overtime pay. Your finished application will look something like Figure 7.
In creating this application, you will learn how to
Though you can do a great deal through wizards, forms, and drag-and-drop features, you still need to write some lines of code for the functionality of the application. The following sections explain some of these lines of code.
Click File from the main menu and select New Project. The Project wizard starts. Next, select General in the Categories window and select Java Application in the Projects pane. Click Next. In the next window, you can leave the suggested project name or specify another name. Choose a Location and Folder for this application. Deselect the Create Main Class box. Now click Finished, which takes you to the main program.
To begin creating the GUI, you are going to start the Form Editor by creating a top container for your application using a specific form. The Java API provides GUI components, often referred to as Swing, and provides three useful top-level container classes:
Select the File menu entry, then select New File, and select Java GUI Forms from Categories. Notice the File Types that appear to the right. For this application, you will use a JFrame Form. Select JFrame Form, then click Next. Name the JFrame SamplesJFrame class. Double-click SamplesJFrame so that it opens in the Source Editor on the right. You'll notice that the code has been generated.
In the middle section of the workspace window, you should see three tabs as well as two buttons that allow you to toggle between the Design view, which gives you a visual view of your application, and Source view, which allows you to work with the raw code. In other words, you are switching from the forms GUI drag-and-drop editor to the code editor. Each editor gives you slightly different options on the menu bar, as shown in Figures 9 and 10.
Click into Design view to use the Form Editor as shown in Figure 9. Now you can begin the process of building the GUI interface. You've started this application with the
From this editor, you will add and edit components by using three panes that are docked at the sides of the IDE (see Figure 11):
As you use components from the Palette, NetBeans automatically generates code, instantiating those objects. If you change the components' properties by using the Properties pane, that code is also generated. You'll notice as you look at the Source Editor that this generated code appears as blue guarded blocks. It is recommended that you not change this code. However, you can modify the way initialization code is generated and even write custom code to be placed within the initialization code. For this tutorial, do not change the generated code.
So far, you have created a project and a JPanel in the Palette, then click in the main area of the JTabbedPane. Note that a new tabbed pane has been added to JTabbedPane. Add another JPanel, making sure that you select jTabbedPane1[JTabbedPane] in the Inspector window. Then hold down the Shift key and click on JPanel in the Palette, then on the frame in the workspace. Another tab appears. You can add as many tabs as you like, but this tutorial covers only two.
Click on any of the objects in the Inspector pane, and you'll see that the properties for each component appear in the Properties pane. In addition, you can right-click the components in the Inspector pane and select Properties from the menu to make the Properties pane pop up.
To change the print for each tab, click on the corresponding To see the code generated for your application so far, click on Source from the middle pane in the menu, as shown in Figure 10. The Source Editor reveals guarded code, which by default is shaded in blue background, as well as code that you can add to or change. As you look through the code, you may notice that you can collapse or expand trees of code as you add to this file.
You may have observed that a layout manager also has been added just beneath the
Return to the Design view, and you should now have an application that reveals two tabs with the titles that you input in the Properties box for the JPanel object. For this application, you'll need to add eight labels, two text fields, and a button. The labels contain information for what the user should enter and for what will appear when the user clicks the button. The text fields are editable for user input. The components need to be arranged on this panel in a way that makes sense. The usual layout managers are available to you. For this arrangement, GridBagLayout is ideal. The GridBagLayout manager allows you to arrange components in a number of ways, and the new customizer makes this really easy to do.
Once you've added the components, you'll need to arrange them on the panel. Right-click the Within the GridBagLayout Customizer, you can drag and drop the representation of your components in the window on the right and arrange them in the order you want. In the left side of the Customizer, use the buttons to anchor objects, add padding and fill, and so forth. You can also change the field entries in the upper part of that area to make the same changes if you know what to enter. Play around with the Customizer until the components are aligned the way you want them. Once you have arranged the components the way you want them, click Close. Now you can change the names of some of those variables to more appropriate titles. To rename the variables, right-click each in the Inspector pane and select Rename. Type in the new name and click OK. Once you have laid out the component the way you want, you may want to change the properties of some of those objects and check the properties of the text fields to be sure that the user can enter information in them. In addition, you need to have text appear on the labels so that the user knows what to enter or what to expect to appear after clicking the button. In the Properties pane for each label, enter the text for each variable as follows:
The application calculates the amount of regular pay, overtime pay, and the total pay the user is to receive and writes these amounts to The refactoring tool goes to work and makes all the necessary changes based on your single entry. Refactoring is the restructuring of code, using small transformations, where 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. A refactored expression must produce the same result, and the refactored program must be functionally equivalent with the original source. Some common reasons for refactoring code include the following:
NetBeans provides the following features for refactoring:
When writing code in a simple text editor, you would have to compile the code frequently to see what your GUI looks like. NetBeans has a preview feature that allows you to see how your application looks with a simple click of the Test Form button located on the center menu as shown in Figure 13. Click the Test Form button, and a test application pops up, showing your creation. You can see from this test whether you need to readjust any of the objects on the panel by going back to GridBagLayout Customizer.
If you would like to compile and run the application, that also is a simple process. Go to the Build menu (see Figure 14) at the top of the IDE and select Clean and Build Main Project. Notice the output at the bottom window. Once the build is complete, you can run the application by returning to the Source view or clicking in the Inspector window on You may have had errors show up in the output window at the bottom of the screen from typos in your code. In an application this small, errors tend to be fairly easy to troubleshoot. In longer programs, though, you may want to use some of the debugging features that NetBeans provides. One such feature is called breakpoints.
Within the NetBeans IDE, you debug by setting breakpoints and watches in your code and running it in the debugger. You can execute your code one line at a time and examine the state of your application in order to discover any problems. When you start a debugging session, all of the relevant debugger windows appear automatically at the bottom of your screen. You can debug an entire project, any executable class, and any A breakpoint is a flag in the source code that tells the debugger to stop execution of the program. When your program stops on a breakpoint, you can perform actions like examining the value of variables and single-stepping through your program. The Source Editor indicates a breakpoint by highlighting the line in red and placing an annotation in the left margin. Except for line breakpoints, all Java breakpoints are defined globally for all IDE projects. For example, if you set a breakpoint on a class, the IDE will stop execution every time it encounters that class during a debugging session regardless of what project you are debugging. To set a line breakpoint, click the left margin of the line in the Source Editor or press Ctrl-F8. You can set other types of breakpoints as well, such as the following:
This sample application is small for taking advantage of these rich features, but as you add to this application, you should consider experimenting with breakpoints for debugging. You can set a few breakpoints at the method you are going to write soon to see how they work. For more details on the NetBeans debugging tool, see For More Information at the end of this tutorial. So far, this application is a simple GUI and no more. It doesn't yet have functionality. You will add an event handler for the button soon, but first create a top menu for the application. Though menus are often one of the first objects created in an application, you're creating the menuing system now to demonstrate how easy it is to move around within your application, creating in whatever order you need, without messing up code. This is one of the big advantages of the Inspector window: the way you can click on any object within your application, add to it, or move around within it.
Return to Design view, go to the Inspector window, and select the
Next, in the Inspector pane, right-click the
The last item to complete in the GUI portion of this application is the Images pane (see Figure 15), so that you know how to add images easily. One way to
display images is by decorating Swing components, such as labels, buttons, and tabbed panes, with an icon -- a fixed-sized picture. An icon is an object that adheres to the Icon interface. Swing provides a particularly useful implementation of the Icon interface: One statement creates the image icon, and two more statements include the image icon on each of the two labels:
NetBeans allows you to display images in similar fashion, but you can do it through the Palette and Properties windows. You don't have to write the code for it. For the Images pane, you'll use a
Begin either by clicking on the Images tab in the Design view or by clicking on the
Next, create another label and place it in the center of the http://java.sun.com/developer/onlineTraining/new2java/newjava.gif or select File and type in the path to the file on your system in the Name text area. Note: If you're on a system that is behind a firewall, you'll have to have your system HTTP proxy settings correct before NetBeans will be able to display the preview of this .gif file (when using the URL method). You should see an image appear in the preview window. Click OK. If you return to Source view and compile the application, you will see the following lines of code, including exception handling statements:
Now the GUI is complete, but the application still doesn't do anything. Next, you need to give it functionality. Click back into Design view and then on to the Pay Calculator pane.
Java technology programs rely on events that describe user actions. These events are represented by objects that a user initiates, such as text entered, a button pushed, or a mouse moved over a component. The component must listen for an event if you want to handle the event with an action, such as displaying text or writing to a database. Without an IDE, you'd have to follow these steps to create event handlers:
When a user fires an event through a GUI component, a method call is made to any objects that have been registered with the component
as listeners for the type of event that took place. An event listener is an object that is notified when an event occurs. Events generated from buttons and text fields need the class to implement the
NetBeans simplifies creating event handlers by creating much of the code for you. You need to know which interface you'll need to implement, and then you'll need to write the code for the logic that goes into the Go to Design view and click the button you created, then right-click. Select Events, then Action -> actionPerformed(computePayActionPerformed). In Source view, you'll see that the following lines of code have been added to register the button with a listener:
NetBeans has also added the necessary method:
Now, add code where indicated to provide the logic of what the application needs to do to compute the amount of regular pay and overtime pay. First, you'll need set up a few variables for the following:
Later, you'll also need variables for
Because the user is entering the information into the text field, that data comes in as a
The classes you'll need to be familiar with are
A common need is to convert strings to numerical values. Once these are converted, you can manipulate that value like any other data primitive (for instance, an
To convert a The following list shows the mapping from primitive type to wrapper class. In almost all cases, the wrapper class has the same name as the primitive data type, with the first letter capitalized:
Each of these wrapper classes, except the
converts the contents of the
There is one exception: The
If the
The For instance,
results in
You can control display format and arrange input into the needed output format by using the The class has methods for three standard formats:
To format a primitive, start by returning an object of type
To be certain the amount is formatting correctly for a specific country, you specify the locale this way:
The result is
To compile these, you'll need to import the following packages and add them to the top of the file:
Read the comments in the code, which gives some explanation. If you are new to using if-statements, read if/else and switch statements, which is a part of the Java Technology Fundamentals newsletter.
Add the following code to your
Compile and run the application. Test it out by entering hours worked and pay rate, such as 33.00, and so forth. Your application should look something like Figure 18. The blue type was created simply by editing the properties of that label so that the foreground appears blue.
The menus are still nonfunctional as well, and you'd follow the same procedure to add events to your menu items. In the Inspector or Project window, select the menu ExitItem, right-click, select Events, choose Action -> actionPerformed. You'll be sent to the Source Editor, where you can enter the following code:
Select Clean and Build Project, then run your application, closing it with the Exit menu. Follow the same procedure for each menu item and any other objects that require functionality. If there are any objects you don't want in your application, select the object in the Inspector window. Right-click and select Delete. You'll be asked if you're sure that you want to delete the item. Say yes, and the item will disappear from view. Build and Clean, then run your application. Try this by deleting OpenItem from the menu. You'll see that cleanup is an easy process. Documenting your application is always a good idea, especially if many people are working on one project. Again, this sample application is a bit small for a good demonstration of the Javadoc tool feature, but you can get a good idea of the kind of information that goes into the documentation and see how NetBeans does all the hard work for you.
Click on the Files tab, then on your You have completed a small desktop application and learned some of the basics of the NetBeans IDE. A big advantage of using the NetBeans IDE platform is that you won't outgrow it. As your development knowledge and skills build, you can delve into other Java technologies and platforms, such as web development using Java Platform, Enterprise Edition or Java Platform, Micro Edition. In addition, NetBeans is extensible, meaning that many of the extensions, or modules, that work in NetBeans also work seamlessly within other products, such as Sun Java Studio Creator and Sun Java Studio Enterprise. The IDE evolves with your needs and experience, and you build on the experience you gain using a common IDE platform, rather than having to learn an entirely new toolset as your needs change. For More Information
|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||