# Informatics Practices for Class XI (CBSE)/Netbeans IDE

NetBeans IDE An Introduction to NetBeans
Most developers recognize NetBeans as the original free Java IDE. It is that, and so much more. The NetBeans IDE provides support for several languages (C, C++, JavaScript, etc.) and frameworks. NetBeans is an open-source project dedicated to providing rock solid software development products (such as NetBeans IDE and NetBeans Platform) that address the needs of developers, users and the businesses who rely on NetBeans as a basis for their products. The NetBeans project is also a vibrant community where people from just about any country you can think of, have the ability to ask questions, give advice, make a wide variety of contributions and ultimately share in the success of our products. On our mailing list, you will find posts from students, developers from top companies, and individuals looking to sharpen their skills.
The startup screen of the NetBeans IDE
The NetBeans IDE In June 2000 NetBeans was made open source by Sun Microsystems, which remains the project sponsor. Please see our History section for a more detailed information. The two base products are NetBeans IDE and NetBeans Platform. Both products are free for commercial and non-commercial use. The source code to both is available to anyone to reuse as they see fit within the terms of use. The legal section contains all information regarding licensings, copyright issues, privacy policy and terms of use. Complete product information can be found under in the Products section. The NetBeans community is healthy and growing thanks to the individuals, companies and complementing products (see the Partners page) that are making NetBeans a success. If you want to join, you may register for free. With over 18 million downloads of the NetBeans IDE to date, and over 500,000 developers participating, the netbeans.org project is thriving. Each month visitors from over 130 identifiable countries use and contribute to NetBeans. In Press Center you can find and review NetBeans press releases and articles where NetBeans' name has appeared in the media. If we have missed something let us know and we will add it to our news section. Vision Statement of the NetBeans Open Source Project A look back
Let's look a little into the past. NetBeans started as a Java IDE. At the beginning it was like every other IDE with an editor, GUI designer, debugger, etc. The IDE was written in Java and it ran on any platform. The people writing it were developing NetBeans using NetBeans (they still are). After a while the IDE began to evolve in some interesting ways: Open APIs were introduced to make the IDE extensible. The team developing it grew. NetBeans was open sourced. Developers began to use various tools to manage the code. In each case, it proved worthwhile to integrate the tools used to develop the IDE into the IDE itself. The result is that NetBeans contains things like version control support, building using ANT, Javadoc search and generation and more. Each new integration showed the strengths and weaknesses of the APIs. As a result, the APIs were evolved to be increasingly generic, to accommodate the maximum number of use cases, while making the minimum assumptions about those use cases. More and more the developers worked to make NetBeans not just a Java IDE, but a platform for tools no matter what language or technology was being used. NetBeans became more of a platform, integrating a huge variety of tools into a seamless environment, enhancing, not compromising, the usefulness of those tools by themselves. This turned out to be even more valuable than it seemed. For example, when you integrate a debugger from one place, source control system from another, and a code browser from a third into the same environment, you end up with something greater than the sum of its parts. And so the concept of a "tools platform" was born. IDEs and Platform
IDE stands for Integrated Development Environment. Integration in old-fashioned, monolithic IDEs meant a set of tools are available as part of a single program. Yet development today needs more than this kind of integration. A better meaning for integration can be had by looking at the modern software development process. Applications and application development • Are multiplatform and distributed - various OS's, servers, workstations, handheld devices, etc. • Are multi-language - Java, HTML, C/C++, Perl, Python, etc. • Use various technologies and standards - databases, XML, Servlets, JSP, UML, ... • Go through many stages - such as design, modelling, implementation, documentation, deployment and support. • Are developed in a variety of styles - from individuals, to small teams, to large distributed teams, to open source. A really good, useful IDE should work with the tools used by people playing different roles in a project, integrate them and make them available as a part of one environment. An IDE should cover all aspects of the application and stages of the development cycle, and which can be used by all members of the development team. Providing tools for all the aspects of development, and integrating them in the deeper sense of the word is not an easy task. Therefore, our goal is to create a Platform which achieves these goals, and let everyone add their own tools to it. We know that there is no "one size fits all" IDE - so it is better to empower developers and teams to customize the IDE to meet their unique needs. Where we are going We must ensure the NetBeans Platform is solid, stable, performant and backward compatible, since it is the foundation of other projects. At the same time we have to work toward maximum extensibility and the most generic and flexible framework possible. We will continue to develop and release NetBeans IDE and focus on making it a powerful and popular IDE for developing in Java and other languages. We will improve NetBeans simultaneously in all areas in an iterative way. There will be times when the above goals contradict each other, e.g. purity of the APIs vs. backward compatibility vs. performance vs. genericity - these are not always compatible. Especially in such cases the community should determine the right course of action in broad discussion, preserving backward compatibility where possible, and providing workarounds to keep existing integrations effective. We will to encourage use of NetBeans IDE for development with any language or technology. Addition of support for new languages and technologies will continue. We will continue to make the sources public under a very liberal license which will allow both individuals and companies to benefit from participating in the project. By providing a safety blanket - the source code is always available, and the license does not prohibit modifications to it - those who integrate with it can feel comfortable because they are not at risk of vendor lock-in. We will continue to grow the NetBeans community We believe that it is not possible to achieve these goals without a thriving community. NetBeans is developed as an open source project. We believe that this development model is ideal for building such a platform. Every piece of information, every special case, every experience integrating something new reveals new paths and new possibilities. Community-based, public development allows everyone to benefit from each other's experiences. Something that develops from this process is "institutional memory". We need to learn from our experiences, and incorporate the lessons learned into what we do next. Community makes that happen. NetBeans IDE 6.5.1 Installation Instructions
This document describes how to install NetBeans IDE 6.5.1 on your system. Required Software Before you install the IDE, the Java SE Development Kit (JDK) 5 Update 16 (version 1.5.0_16) or newer (including JDK 6 Update 11) must be installed on your system. If you do not have an installation of JDK, you cannot proceed with the installation. You can download the latest JDK version at http://java.sun.com/javase/downloads. For PHP, Ruby, and C++ download options, you can install JRE instead of JDK. However, if you are planning to use any Java features, you will need JDK. Installing the Software Follow the instructions in this section to install the IDE on your system. These installation instructions apply to all supported platforms. For the list of supported platforms, see the NetBeans IDE 6.5.1 Release Notes. Microsoft Windows, Solaris OS, and Linux To install the software: 1. After the download completes, run the installer. o For Windows, the installer executable file has the .exe extension. Double-click the installer file to run it. o For Solaris and Linux platforms, the installer file has the .sh extension. For these platforms, you need to make the installer files executable by using the following command: chmod +x ./<installer-file-name> 2. To choose the tools and runtimes to install, perform the following steps at the Welcome page of the installation wizard: a. Click Customize. b. In the Customize Installation dialog box, make your selections. c. Click OK. At the Welcome page of the installation wizard, click Next. At the License agreement page, review the license agreement, select the acceptance checkbox, and click Next. At the NetBeans IDE installation page, do the following:
Note: The installation directory must be empty, and the user profile you are using to run the installer must have read/write permissions for this directory. a. Accept the default JDK installation to use with the NetBeans IDE or select a different installation from the drop-down list. If the installation wizard did not find a compatible JDK installation to use with the NetBeans IDE, your JDK is not installed in the default location. In this case, specify the path to an installed JDK or cancel the current installation, install the required JDK version, and restart this installation. b. Click Next. If the GlassFish V2.1 application server installation page opens, do the following:
Note: The installation directory you specify must be empty, and the user profile you are using to run the installer must have read/write permissions for this directory. a. From the list of compatible JDK installations, choose the JDK you want the application server to use or click the Browse button to specify another JDK installation. b. Change the username and password for the default server domain or accept the defaults and click Next. The default username and password are admin and adminadmin. c. Verify the default port values (HTTP, HTTPS, and Admin) for the server or change them if necessary. d. Click Next. If the GlassFish v3 Prelude application server installation page opens, accept the default installation directory or specify another installation location. If the Apache Tomcat installation page opens, accept the default installation directory or specify another installation location. At the Summary page, verify that the list of components to be installed is correct and that you have adequate space on your system for the installation. Click Install to begin the installation. When the installation is complete:
a. If the GlassFish application server has not been installed, select the Register the NetBeans IDE after finishing the installer checkbox to register the NetBeans IDE. b. Click Finish to exit the wizard. If you selected the Register... checkbox at the previous step, the Registration page opens in the browser. Click Register. Enter your Sun Online Account or create it on the www.sun.com page, which is accessible via a link. Note: If you encounter problems successfully completing the software installation, see Troubleshooting for descriptions and suggested workarounds for unresolved issues that could affect the installation process. Note: If you have not registered the GlassFish application server right after the installation, you can do it when you run the NetBeans IDE or open the Admin console of the GlassFish application server. Note: If you have not registered the NetBeans IDE 6.5.1 right after the installation, you can do it when you run the NetBeans IDE. Using NetBeans 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. NetBeans IDE Nuts and Bolts
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. Features and Tools
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 • Syntax highlighting for Java, JavaScript, XML, HTML, CSS, JSP, IDL • Customizable fonts, colors, and keyboard shortcuts • Live parsing and error marking • Pop-up Javadoc for quick access to documentation • Advanced code completion • Automatic indentation, which is customizable • Word matching with the same initial prefixes • Navigation of current class and commonly used features • Macros and abbreviations • Goto declaration and Goto class • Matching brace highlighting • JumpList allows you to return the cursor to previous modification GUI Builder • Fully WYSIWYG designer with Test Form feature • Support for visual and nonvisual forms • Extensible Component Palette with preinstalled Swing and AWT components • Component Inspector showing a component's tree and properties • Automatic one-way code generation, fully customizable • Support for AWT/Swing layout managers, drag-and-drop layout customization • Powerful visual editor • Support for null layout • In-place editing of text labels of components, such as labels, buttons, and text fields • JavaBeans support, including installing, using, and customizing properties, events, and customizers • Visual JavaBean customization -- ability to create forms from any JavaBean classes • Connecting beans using Connection wizard • Zoom view ability Database Support • Database schema browsing to see the tables, views, and stored procedures defined in a database • Database schema editing using wizards • Data view to see data stored in tables • SQL and DDL command execution to help you write and execute more complicated SQL or DDL commands • Migration of table definitions across databases from different vendors • Works with databases, such as MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft SQL Server, PointBase, Sybase, Informix, Cloudscape, Derby, and more 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. Getting Familiar With NetBeans
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.
Figure 1. Welcome Screen
Once you tell NetBeans the name of a new project, it then: • Creates a source tree with an optional skeleton class inside • Creates a folder for unit tests • Sets classpaths for compiling, running, and testing • Sets the Java platform the project is to run on • Creates an Ant build script (build.xml), which contains instructions that the IDE uses when you perform commands on your project, such as compile or run Click File from the main menu and select New Project. The New Project wizard pops up and looks similar to Figure 2.
Figure 2. New Project Wizard
Figure 3. Files Window 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, as shown in Figure 3 above. 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.
Figure 4. Source Editor
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 similar to the one in Figure 4. 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. Using the Source Editor
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 as in Figure 5. For more information on editing features in the IDE, see Java Editing Enhancements in NetBeans IDE 6.0
Figure 5. Add Property Dialog
Refactoring
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: • To make the code easier to change or easier to add a new feature • To reduce complexity for better understanding • To remove unnecessary repetition • To enable use of the code for other needs or more general needs NetBeans provides the following features for refactoring: • Finds where classes, variables, and methods are used throughout the source code in your project. • Enables you to move a class to another package or into another class and enables you to move a static field or a static method from one class to another. In addition, it updates all source code in your project to reference the element in its new location. • Enables you to change the name of a class, variable, or method to something more meaningful. In addition, it updates all source code in your project to reference the element by its new name. • Generates a 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. • Enables you to add parameters to a method and change the access modifier. • Enables you to roll back all the changes in all the files that were affected by the refactoring. 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. Debugging
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. Figure 6 shows two breakpoints; a line breakpoint is denoted by a red square, and a field breakpoint is displayed as a triangle.
Figure 6. Breakpoints in Source Editor 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: • Method -- Program execution stops every time the method is executed. • Exception -- You can break whenever a specific exception is caught, whenever a specific exception is not handled in the source code or whenever any exception is encountered regardless of whether the program handles the exception or not. • Variable -- You can stop execution of your program whenever a variable in a specific class is accessed (for example, the method was called with the variable as an argument) or modified. • Thread -- You can break program execution whenever a thread starts, stops, or both. • Class -- You can break when the class is loaded into the virtual machine, unloaded from the virtual machine, or both. 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. Importing Existing Java Source Code Into NetBeans
You can use two project templates to import your existing source code: • Java Project With Existing Sources -- Use this project template to create a standard Java project. A standard Java project uses the IDE to compile, run, and debug your application. • Java Free-From Project -- Use this project template if you want to use your own Ant script to compile, run, and debug your application. The following steps cover use of the first template to create a standard Java project without the use of existing Ant scripts. 1. Choose File > New Project (Ctrl-Shift-N). 2. Choose Java > Java Project With Existing Sources. 3. Click Next. 4. In the Project Name field, type a name for your project. Notice that the IDE automatically suggests a name for the project folder. 5. Click the Browse button next to the Project Folder field and create a folder somewhere on your system for your NetBeans projects. Then select the newly created NetBeans projects folder. Be sure to select the Set as Main Project box, then click Next. 6. In the Existing Sources pane, click Add Folder, navigate to the directory of source files, and select the resources and src folders. 7. (Optional) In the Test Packages Folder pane, click Browse to select the folder containing the JUnit package folders. 8. Click Finish. Your project will now be displayed in the Projects and Files windows. Managing the Classpath NetBeans automatically adds everything on your project's compilation classpath to the project's runtime classpath. To manage a project's classpath: 1. In the Projects window, right-click the project's node and choose Properties. 2. In the Project Properties dialog box, click the Libraries node in the left pane. 3. Select the Compile tab in the dialog box's right pane. 4. Add the necessary elements to the project's compilation classpath by clicking the appropriate button. You can add any of the following: o Project. The JAR file or WAR file produced by another project, as well as the associated source files and Javadoc documentation o Library. A collection of JAR files or folders with compiled classes, which can optionally have associated source files and Javadoc documentation o JAR file. A JAR file somewhere on your system
Creating, Compiling, and Running an Application
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.
Figure 7. Pay Calculator application Your finished application will look something like Figure 7. In creating this application, you will learn how to: • Use the Form Editor • Use the Source Editor • Use the Palette, Inspector, and Properties features • Add event handlers • Compile and run your application 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. Creating the Pay Calculator Application
Start by creating a new project for the application. 1. Click File from the main menu and select New Project. The Project wizard starts. 2. Select Java in the Categories pane and select Java Application in the Projects pane, as shown in Figure 2 above. Click Next. 3. 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. 4. Click Finish. The IDE creates the new project and displays it in the Projects and Files windows. 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. 1. From the File menu select New File. The File wizard displays. 2. From Categories select Swing GUI Forms. Notice the File Types that appear to the right. For this application, you will use a JFrame Form. Select JFrame Form, then click Next. 3. Name the JFrame 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, as shown in Figures 8 and 9.
Figure 8. GUI Design Editor tool bar
Figure 9. Source Editor 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.
Figure 10. NetBeans IDE Work Environment From this editor, you will add and edit components by using three panes that are docked at the sides of the IDE (see Figure 10 above): • Palette -- Contains JFC/Swing, AWT, layout managers, and JavaBeans components. • Inspector -- Displays a tree hierarchy of all components contained in the currently selected file, including visual components and containers, such as buttons, labels, menus, and panels. It can also include nonvisual components, such as timers and data sources. • Properties -- Displays the properties of the component currently selected in the Inspector, Editor, Projects, or Files windows. You can also right-click a component to pop up a properties box for that component. 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. 1. Click on Tabbed Pane in the Palette, then click on the blank square in the design form. This creates a JTabbedPane. Notice that all the components you've created are listed in the Inspector window. 2. Click on Panel in the Palette, then click inside the 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. 3. Add another 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. Your Inspector window should now look similar to Figure 11, and the components in your Design Editor should look like Figure 12 below.
Figure 11. Inspector Window
Figure 12. Design Editor displaying a Tabbed Pane
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, as shown in Figure 9 above. 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.
Figure 13. Guarded Generated Code
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. What's a Layout Manager?
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: In the Palette, click on Label, then click inside the jPanel1 area in the Design Editor. This adds a JLabel to the form. Repeat this procedure seven more times, so there are eight new labels in total. Don't worry about where the components appear in the workspace for now or what variable names they've been given. You are going to work on those in a moment. Click on Text Field in the Palette, then click inside the jPanel1 area in the Design Editor. Do this again, so there are two JTextFields in total. Add a 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]
Figure 14. Design Editor Displaying Renamed Components
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. Arrange your components so that they appear similar to Figure 14. 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. Checking Your GUI
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, as shown in Figure 8. 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. Adding Menus and Images
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. In the Inspector pane, right-click the JFrame listed and choose Add From Palette > Swing Menus > Menu Bar. This adds a JMenuBar. Expand the 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. In the Inspector, right-click jMenu1 and choose Add From Palette > Menu Item. This creates a JMenuItem. Rename the component to 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). Change the default text for 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. Create another menu item by following the previous three steps. Change the component name to ExitItem, and change the default text to Exit. In the Inspector, double-click on JFrame, then click on jMenuBar1. Your menu bar should now look like the one in Figure 15. The last item to complete in the GUI portion of this application is the Images pane (see Figure 17), 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.
Figure 15. Menu Bar
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. Click on the JPanel object for the Images tab in the Inspector (or click on the Images tab in the Design Editor). Add a JLabel to the Images panel by clicking on Label in the Palette, then clicking inside the Images JPanel area in the Design Editor. Download this sample image and save it to a location on your computer. In the Properties window, click the ellipsis button (...) for the icon property. A dialog displays, allowing you to locate and set the image to the property. Make sure 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 (Figure 16). Click OK. In the Design Editor, click on the JLabel's default text that now appears next to the image. Delete it.
Figure 16. Inspector window Click here for a larger image.
Figure 17. Images Pane
When you click on Preview Design ( ), your GUI should now look similar to Figure 17 above. 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. Adding Event Handlers
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: Decide which type of event is fired by a component and implement the right interface Register the component as a listener for that type of event Implement handler methods from the interface
Figure 18. How Events Work
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 {
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 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.parseBoolean(aString); // the Boolean method is only available in Java 5+
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 {
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) {
} else {
//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 (Figure 19), 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. Your application should look similar to Figure 7 above.
Figure 19. Fix All Imports Dialog
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:
} 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 Work
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. Summary
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.