By Dana Nourie, May 22, 2005, Updated July 2008
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 6.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 6 and NetBeans 6.1 separately to ensure that you have the latest versions.
Because the NetBeans IDE is open source is undergoing continual improvement, you may notice slight differences between the screen captures in this article and the latest download. This tutorial is based on NetBeans 6.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
Goto
declaration and Goto
classGUI 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.
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:
build.xml
), which contains instructions that the IDE uses when you perform commands on your project, such as compile
or run
From there, you can choose the type of application you want to create by selecting a category such as Java, Web, or Enterprise. Notice that within the Java category, you can create a project containing an empty application. Choose Java 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 Projects 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. The Files tab shows a directory-based view of your project. 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:
nbproject/build-impl.xml
-- Contains the instructions for handling your project. The IDE generates this file, which you should not edit.build.xml
-- Imports targets from build-impl.xml
. You can edit this file to override existing targets or create new targets.Tip:
Many menu commands such as Run and Build have keyboard shortcuts to the main project. You can also access all commands for individual projects by right-clicking their project nodes in the Projects window.
The Files folder also contains the output folder for compiled classes, JAR files (for Java SE projects) or WAR files (for web projects), and Javadoc. This displays as a build
folder after you compile the application.
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 Services window lists various facilities available to your project, such as servers, databases, enterprise beans, and web services. 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 window after you have written, compiled, run, tested and debugged your applications.
Return to the Projects window. Notice the file system that has been created. Files and directories associated with an application project are organized in a logical fashion. Double-clicking a source file automatically opens the file in the workspace to the right, bringing up the appropriate Source Editor.
"Double-click the Main.java
source file to see the Source Editor.
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 provides suggestions for code-completion as you type.
You can customize colors in the highlighting by going to Tools > Options (NetBeans > Preferences on a Mac) > 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 deactivate it more permanently by going to Tools > Options (NetBeans > Preferences on a Mac) > Editor > General, and under Code Completion, deselecting the Auto Popup Completion Window checkbox.
You can also save time by assigning abbreviations that the Source Editor expands for you. To set abbreviations, go to Tools > Options (NetBeans > Preferences on a Mac) > Editor > Code Templates. Type the first few letters of an abbreviation and press the spacebar. The Source Editor then expands the abbreviation.
Turn on line numbering easily by right-clicking in the Source Editor's left sidebar and selecting Show Line Numbers.
When programming in Java, you can add to your source code by making use of commonly-used code templates. Press Ctrl-I in the Source Editor to view the Insert Code pop-up menu. Add properties to classes, create constructors, generate accessor methods, and override methods from superclasses. When adding properties, the IDE provides you with a dialog.
For more information on editing features in the IDE, see Java Editing Enhancements in NetBeans IDE 6.0
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:
getter
method and a setter
method for a field and optionally updates all referencing code to access the field using the getter
and setter
methods.To view the Refactor menu, right-click and choose Refactor from an item in the Projects window, or right-click and choose Refactor of an opened file in the Source Editor.
Within the NetBeans IDE, you can debug by setting breakpoints and watches in your code, then running your application 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 JUnit
tests. The IDE also lets you debug applications that are running on a remote machine by attaching the debugger to the application process.
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 on the left margin of the line in the Source Editor. A line breakpoint is denoted by a red square, and a field breakpoint is displayed as a triangle.
You can customize a breakpoint by right-clicking on the breakpoint icon and choosing Breakpoint > Customize. The Customizer dialog enables you to set conditions and actions on the breakpoint. You can set other types of breakpoints as well, such as the following:
To run the debugger tool, click the Debug Main Project icon in the main tool bar, or choose Run > Debug Main Project from the main menu. For a quick demonstration of the debugger tool in action, see Demo of JDK Debugging.
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.
JUnit
package folders.Your project will now be displayed in the Projects and Files windows.
NetBeans automatically adds everything on your project's compilation classpath to the project's runtime classpath. To manage a project's classpath:
Now that you're familiar with the nuts and bolts of the NetBeans IDE, the next sections will step you through creating, compiling, and running an application that uses a simple GUI interface with some background functionality that calculates the rate of regular and overtime pay.
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.
Start by creating a new project for the application.
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: JFrame
, JDialog
, and JApplet
. Every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and added to the second. Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI. You have the option to add a menu bar to a top-level container.
Start by using the File wizard to create a JFrame component.
SamplesJFrame
, and click Finish.To see what the wizard has created, click on the Files tab and expand the nodes listed under the new project. Double-click SamplesJFrame
to view the file in the Source Editor on the right.
Above the Source Editor, you should see 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 can switch from the GUI drag-and-drop editor to the code editor. Each editor gives you slightly different options in the tool bar.
Click into the Source view to see the code that has been generated for the class. Then click back into the Design view to use the Design Editor. You can now begin the process of building the GUI interface.
You started this application with the JFrame
container. Now you can easily add other components to it by selecting a component from the Palette and placing it in the Design Editor. Changing component properties is just as easy.
From this editor, you will add and edit components by using three panes that are docked at the sides of the IDE:
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 JFrame
class called SamplesJFrame
. Next, you'll build on the JFrame
component and add other components.
JTabbedPane
. Notice that all the components you've created are listed in the Inspector window.JTabbedPane
in the editor (you may need to resize the JTabbedPane
so it is larger. A JPanel
is created. Note that a new tabbed pane has been added to JTabbedPane
.JPanel
to the JTabbedPane
in the Design Editor. 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 window and select Properties from the menu to make the Properties window display.
To change the text for each tab, click on the corresponding JPanel
in the Inspector window. For instance, click on jPane11
to select it. Next, go to the Properties window on the right and scroll down until you see the Tab Title
listed. Click on the ellipsis button ( ...
) at the right, and a window pops up that allows you to replace the current text. Type in Pay Calculator
and click OK. Notice that the text instantly appears in the Design view on the tab. Now change the text for jPanel2
; select it in the Inspector window, then in the Properties window enter Images
in the Tab Title
field.
To see the code generated for your application so far, click on Source in the tool bar above the Editor. The Source Editor reveals guarded code, which by default is shaded in grey background, as well as code that you can add to or change. As you examine the code, you may notice that you can collapse or expand segments of code as you add to this file.
You may have observed that a layout manager also has been added just beneath each JPanel
you added. You can easily change the layout manager for components from the Inspector. For example, right-click on jPanel1
, and note the options listed from Set Layout. The IDE's GUI builder, named Matisse, uses the Free Design layout manager by default. This layout manager uses simple layout rules that are easy to work with.
A layout manager is an object that implements the LayoutManager
interface and determines the size and position of the components within a container. Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container. See A Visual Guide to Layout Managers.
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
objects. If necessary, resize the jTabbedPanel
so that it fills the entire JFrame
that contains it.
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. While the usual layout managers are available to you, the Free Design layout is ideal for this scenario. This layout manager allows you to arrange components in a number of ways, and the Matisse GUI builder makes this really easy to do.
To begin adding the components to the first jPanel
, select jPanel1
in the Inspector or click on the Pay Calculator
tab in the Design Editor, then do the following:
jPanel1
area in the Design Editor. This adds a JLabel
to the form.jPanel1
area in the Design Editor. Do this again, so there are two JTextField
s in total.JButton
to the form by selecting Button in the Palette, then clicking inside the jPanel1
area in the Design Editor.Once you've added the components, you'll need to rename them, change the default text that each displays, and arrange them on the panel. You can change the default text for components by either double-clicking on the component directly in the Design Editor, or right-clicking a component in either the Design Editor or the Inspector, and choosing Edit Text.
Change the default text for the following components:
Variable | Text |
---|---|
jLabel1 |
Hours Worked: |
jLabel2 |
Rate/ Hour ($): |
jLabel3 |
Regular Pay: |
jLabel4 |
Overtime Pay: |
jLabel5 |
Total: |
jButton1 |
Compute |
To rename a component, right-click it in either the Design Editor or the Inspector and choose Change Variable Name. Change names for the following components:
Variable | Text |
---|---|
jLabel6 |
********** |
jLabel7 |
********** |
jLabel8 |
********** |
jTextField1 |
[blank] |
jTextField2 |
[blank] |
In order to arrange the components the way you want, simply drag the components to their positions in the Editor. Make use of the guidelines that display to align components vertically and horizontally. You can also resize components manually by clicking on their edges or corners.
To edit a component's properties, first select that property, either in the Editor or in the Inspector window. That component's properties automatically appear in the Properties pane. Scroll through the items, changing the text, changing the background or foreground colors as you like, setting column width, and changing any other properties you feel appropriate. Experiment with various properties, changing back to the default whenever you need to.
Because the user will enter information into the two text fields, it would be better to give those objects variable names that reflect the information being entered. Go to the Inspector window, right-click on the first JTextField
object and select Change Variable Name. Type in the name hoursWorked
. Then rename the second JTextField
object rate
.
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 Preview Design located in the Design Editor tool bar. 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 in the Design Editor.
If you would like to compile and run the application, that is also a simple process. You can make use of the icons displayed in the IDE's main tool bar; click Build to compile the application, and Run to run it. Note that you can also build and run an application using the options in the Build and Run menus from the IDE's main menu.
Compile your application now. Notice the output that displays in the Output window at the bottom of the IDE. Once the build is complete, you can try running the application. The application will run and pop up on the screen. A quick way to build is to press F11. You can also press F6 to run the application.
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.
JFrame
listed and choose Add From Palette > Swing Menus > Menu Bar. This adds a JMenuBar
.JMenuBar
that has been added to the Inspector window and notice that two JMenu
objects have been added by default. In the Design Editor, note that the text of the two JMenu
items is File
and Edit
, respectively. While you can use the Properties window to change the values of all properties of a given object, you can often change text directly in the Design Editor. Change the text of the second menu item from Edit
to Help
. You can do so by double-clicking directly on the text in the editor.jMenu1
and choose Add From Palette > Menu Item. This creates a JMenuItem
.OpenItem
. You can do so by right-clicking the component either in the Design Editor or the Inspector and choosing Change Variable Name. If for any reason you have difficulty viewing the menu item in the Design Editor, you can double-click on jMenuBar1
in the Inspector, then click on the first jMenu
component (i.e., with File
text).OpenItem
to Open
. Right-click on the item in the Inspector and choose Edit Text. Otherwise, simply double-click on the default text in the Design Editor and type in Open
.ExitItem
, and change the default text to Exit
.In the Inspector, double-click on JFrame
, then click on jMenuBar1
.
The last item to complete in the GUI portion of this application is the Images pane, so that you learn 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: ImageIcon
, which paints an icon from a GIF, JPEG, or (as of version 1.3) PNG image.
To add an image to the Images panel in your GUI, you can use a JLabel
, and change the icon
property of that object to display the image.
JPanel
object for the Images tab in the Inspector (or click on the Images tab in the Design Editor).JLabel
to the Images panel by clicking on Label in the Palette, then clicking inside the Images JPanel
area in the Design Editor....
) for the icon
property. A dialog displays, allowing you to locate and set the image to the property.Image chooser
is selected in the top drop-down box, then select the External Image option. Click the ellipsis button next to the File or URL field and navigate to the image you saved on your computer. You should see an image appear in the preview pane at the bottom of the dialog. Click OK.JLabel
's default text that now appears next to the image. Delete it.To see the code that was generated when you added the JLabel
and accompanying image, click into the Source view for SamplesJFrame.java
, and you will see the following lines:
jLabel9 = new javax.swing.JLabel();
...
jLabel9.setIcon(new javax.swing.ImageIcon("/Users/nbuser/Desktop/newjava.gif"));
The first statement creates the JLabel
, and the second creates a new ImageIcon
object and attaches the image to it. It then sets the ImageIcon
to the JLabel
.
Now the GUI is complete, but the application still doesn't do anything. Next, you need to give it functionality.
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 ActionListener
interface. When implementing this interface, you must also implement a listener method.
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 listener
method.
Go to Design view and in the editor click the button you created, then right-click and choose Events > Action > Action Performed. You are then taken to the Source view and shown the following:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
Also, the following lines of code have been added to register the button with a listener:
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
Because the user is entering the information into the text field, that data comes in as a String
. You'll need to parse these strings into workable types, such as int
or double
. You'll then need to perform the calculations to determine how many hours are regular and how many are overtime. Once those amounts are determined, you can calculate regular pay and overtime pay, then total those two amounts. Lastly, you'll need to convert the numbers to dollar amounts.
The classes you'll need to be familiar with are Integer
, Double
, and NumberFormat
.
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 int
, float
, or double
). The problem is that when you read from a file, get a command line argument, get an applet parameter, or just prompt for input from a text field on a form, you always start with a String
object. Treating that String
as a primitive requires an extra step, the conversion.
To convert a String
you use a wrapper class. Every primitive has an associated wrapper class. These wrapper classes allow you to treat primitives as objects. In addition, these classes contain methods that permit manipulation of these objects, appropriate for the data type.
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:
byte - Byte
short - Short
int - Integer
long - Long
char - Character
float - Float
double - Double
boolean - Boolean
Each of these wrapper classes, except the Character
class, has a method that allows you to convert from a String
to the specific primitive type. Simply call the method from the appropriate wrapper class, and your String
is converted to a primitive type:
String myString = "12345";
int myInt = Integer.parseInt(myString);
This converts the contents of the String
variable myString
to an int
named myInt
. The conversion is that easy. The only trick is that the conversion for each data type involves a uniquely named method in each wrapper class. All but the Boolean conversions are done by similarly named methods, but still all the method names are different:
byte - Byte.parseByte(aString)
short - Short.parseShort(aString)
int - Integer.parseInt(aString)
long - Long.parseLong(aString)
float - Float.parseFloat(aString)
double - Double.parseDouble(aString)
boolean - Boolean.valueOf(aString).booleanValue();
There is one exception: The Character
class has no such method, so you have to ask String
for the character with the charAt()
method:
// The variable e is the character e in the string Hello
String hello = "Hello";
char e = hello.charAt(1);
If the String
contents cannot be converted to the requested primitive type, then a NumberFormatException
is thrown. This is a runtime exception, so the conversion code does not have to be in a try-catch block.
The NumberFormat
class is used to print the numbers correctly. Printing numbers to the screen can produce some odd or undesired results. For instance:
public class PrintNum {
public static void main(String args[]) {
double amount = 400000.00;
System.out.println("She paid " + amount + " for the house.");
}
}
results in:
She paid 400000.0 for the house.
You can control the display format and arrange input into the needed output format by using the NumberFormat
abstract class in the java.text package
. This class provides the interface to format and parse numbers, and it includes methods to determine which locales have number formats and what their names are.
The class has methods for three standard formats:
getInstance
or getNumberInstance
gets a format for the normal number format, such as 600,000.getCurrencyInstance
gets a format for the currency number format, such as $600,000.00.getPercentInstance
gets a format for displaying percentages, such as 56%.To format a primitive, start by returning an object of type NumberFormat
by calling on one of the above methods.
NumberFormat nf = NumberFormat.getCurrencyInstance();
To be certain the amount is formatting correctly for a specific country, you specify the locale this way:
NumberFormat nf =
NumberFormat.getCurrencyInstance(Locale.US);
The result is:
She paid $400,000.00 for the house.
To compile these, you'll need to import the following packages and add them to the top of the file:
import java.text.NumberFormat;
import java.util.Locale;
Now, back to the application you are building: Add the following code to the jButton1ActionPerformed()
event handler method. Read the comments in the code, which provide some explanation. If you are new to using if/else
statements, read Java Programming Language Basics: if/else and switch statements, which is a part of the Java Technology Fundamentals newsletter.
//Gets how many hours worked from the text field, and then parses it to type int.
int hw = Integer.parseInt(hoursWorked.getText());
//Gets the pay rate entered in the text field, and parses it to type double.
double rateEntered = Double.parseDouble(rate.getText());
//Creates two variables of type double for later use.
double regularPay = 0;
double overTimePay = 0;
//Simple if statement for calculations
if (hw > 40) {
regularPay = 40 * rateEntered;
overTimePay = (hw - 40) * 1.5 * rateEntered;
} else {
regularPay = hw * rateEntered;
overTimePay = 0.0;
}
//Creates a variable of both types of pay combined.
double total = regularPay + overTimePay;
//Creates variables for number formatting
NumberFormat nfRegular = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat nfOverTime = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat nfTotal = NumberFormat.getCurrencyInstance(Locale.US);
//Writes the totals in the correct format to the labels
regularPayField.setText(" " + nfRegular.format(regularPay));
overtimePayField.setText(" " + nfOverTime.format(overTimePay));
totalField.setText(" " + nfTotal.format(total));
After entering the above code, make sure to add imports for NumberFormat
and Locale
. You can do this by right-clicking in the Source Editor and choosing Fix Imports. A dialog displays, showing you the fully qualified class names that match the unrecognized classes used in the file.
Compile and run the application. Test it out by entering hours worked and pay rate.
You'll notice that the menus are still nonfunctional. You can follow the same procedure to add events to your menu items. In the Inspector, right-click ExitItem
and choose Events > Action > actionPerformed. You'll be sent to the Source Editor, where you can see the following code:
private void ExitItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
Type in the following code (changes in bold):
private void ExitItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(1);
}
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. Right-click and select Delete. The item immediately disappears from the view. You can then Clean and Build the application, and run it to verify changes. Try this by deleting OpenItem
. 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. This sample application is a bit small for a good demonstration of the Javadoc tool feature, but the following steps provide you with an idea of the kind of information that goes into the documentation and see how NetBeans does all the hard work for you.
Click into the Files window, then click your project node. Go to the Build Menu and select Generate Javadoc for JavaApplication (or whatever name you gave your project). The IDE generates the Javadoc in the dist
> javadoc
folder, and you'll see output provided in the Output window. Then a browser window pops up with the documentation formatted in HTML. Click on SamplesJFrame
, and scroll down to see the documentation. This application would not require much documentation, but if you continue building in this project or move on to other larger projects, Javadoc will come in handy.
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 technologies and platforms, such as web development, including EJB and web service applications, or mobile applications using the Java Micro Edition (Java ME) platform. In addition, NetBeans is extensible, meaning that many of the extensions, or modules, that work in NetBeans also work seamlessly within other products. 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.