Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
778
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

5.3 Exploring NetBeans IDE 6.8 169

Figure 5.10. The New Java Application wizard.

Application Project. Click on the Next to open the New Java Application wizard, which is shown in Figure 5.10.

Perform the following operation to set up properties for this new project:

Enter a desired project name, such as JavaAppProject in this example, into the Project Name box as the name for this project.

Select a desired location to save this project. In this example, our desired location is C:\ Book9\DBProjects\Chapter 5. You can select any other valid folder to save your project.

Uncheck the Create Main Class checkbox since we do not want to use this class in this application.

Keep all other default settings and click on the Finish button.

When you finish creating a project, it opens in the IDE with its logical structure displayed in the Projects window and its file structure displayed in the Files window, as shown in Figure 5.11.

1.The Projects window is the main entry point to your project sources. It shows a logical view of important project contents, such as Java packages and web pages. You can right click on any project node to access a popup menu of commands for building, running, and debug-

ging the project,as well as opening the Project Properties dialog box.The Projects window can be opened by choosing Window > Projects (Ctrl-1).

2.The Files window shows a directory-based view of your projects, including files and folders that are not displayed in the Projects window. From the Files window, you can open and edit your project configuration files, such as the project’s build script and properties file. You can also view build output like compiled classes, JAR files, WAR files, and

170 Chapter 5 Introduction to NetBeans IDE

Figure 5.11. The logical and file structures displayed in the Projects and the Files windows.

generated Javadoc documentation. The Files window can be opened by choosing

Window > Files (Ctrl-2).

If you need to access files and directories that are outside of your project directories, you can use the Favorites window. You open the Favorites window by choosing Window > Favorites (Ctrl-3). You add a folder or file to the Favorites window by right clicking in the Favorites window and choosing the Add to Favorites menu item.

It can be found from Figure 5.11 that the Java JDK 1.6 has been installed with the NetBeans IDE 6.8 and located in the Libraries folder in this project. If you want to use other Software Development Kits (SDK), JDK, project, or library with your projects, you can load them first, and then add them into your library by right clicking on the Libraries node and select the associated operational menu item from the popup menu.

Next, we need to add a graphical user interface (GUI) with other necessary GUI components to our project, and use it as a user interface to communicate with our project during the project runs.

5.3.2.1.1 Add a Graphical User Interface To proceed with building our interface, we need to create a Java container within which we will place the other required GUI components. Generally, the most popular Java GUI containers include:

JFrame Form (Java Frame Form window)

JDialog Form (Java Dialog Box Form window)

JPanel Form (Java Panel Form window)

In this step, we’ll create a container using the JFrame component. We will place the container in a new package, which will appear within the Source Packages node.

5.3 Exploring NetBeans IDE 6.8 171

Figure 5.12. The finished New JFrame Form wizard.

Perform the following operations to complete this GUI adding process:

1.In the Projects window, right click on our newly created project JavaAppProject node and choose the New > JFrame Form menu item.

2.Enter JavaAppProjectFrame into the Class Name box as the class name.

3.Enter JavaAppProjectPackage into the Package box as the package name.

4.Click on the Finish button.

Your finished New JFrame Form wizard should match one that is shown in Figure 5.12.

The IDE creates the JavaAppProjectFrame form and the JavaAppProjectFrame class within the JavaAppProject application, and opens the JavaAppProjectFrame form in the GUI Builder. The JavaAppProjectPackage package replaces the default package.

When we added the JFrame container, the IDE opened the newly created ContactEditorUI form in an Editor tab with a toolbar containing several buttons, as shown in Figure 5.13. The ContactEditor form opened in the GUI Builder’s Design view, and three additional windows appeared automatically along the IDE’s edges, enabling you to navigate, organize, and edit GUI forms as you build them.

The GUI Builder’s various windows include:

Design Area: The GUI Builder’s primary window for creating and editing Java GUI forms. The toolbar’s Source and Design toggle buttons enable you to view a class’s source code or a graphical view of its GUI components. The additional toolbar buttons provide convenient access to common commands, such as choosing between Selection and Connection modes, aligning components, setting component auto-resizing behavior, and previewing forms.

Inspector Window: Provides a representation of all the components, both visual and nonvisual, in your application as a tree hierarchy. The Inspector also provides visual feedback

172 Chapter 5 Introduction to NetBeans IDE

The Palette

window

The Source

The Design

button

button

The Properties

window

The Inspector

window

Figure 5.13. The opened ContactEditor form.

about what component in the tree is currently being edited in the GUI Builder, as well as allows you to organize components in the available panels.

Palette Window: A customizable list of available components containing tabs for JFC/Swing, AWT, and JavaBeans components, as well as layout managers. In addition, you can create, remove, and rearrange the categories displayed in the Palette using the customizer.

Properties Window: Displays the properties of the component currently selected in the GUI Builder, Inspector window, Projects window, or Files window.

Two more points to be emphasized are about the Palette and the Properties windows.

All Java GUI-related components are located in the Palette window and distributed in the different packages or namespaces.This Palette window contains the following GUIrelated components based on the different packages:

Swing Containers: contains all Java container classes

Swing Controls: contains all Swing-related GUI components

Swing Menus: contains all Swing-related menu items

Swing Windows: contains all Swing-related window classes

AWT: contains all AWT-related GUI components

Beans: contains all JavaBeans-related GUI components

Java Persistence: contains all Java Persistence-related components

5.3 Exploring NetBeans IDE 6.8 173

Relatively speaking, AWT related GUI components are older compared with those components defined in the Swing package, in which all components are defined in a model view controller (MVC) style. The java.awt package contains all basic and fundamental graphic user interface components (AWT). However, the javax.swing package contains extensions of java.awt, which means that all components in the javax.swing package have been built into a model-view-controller (MVC) mode with more object oriented properties (Swing).

The Properties window is used to set up and display all properties about GUI components you added into the container, such as appearances and physical descriptions. Let’s illustrate how to use this window to set up and show each property for added GUIrelated components on this container in the next section.

5.3.2.1.2 Add Other GUI-Related Components Next, let’s finish this GUI by adding some GUI-related components into this GUI container. For this application, we want to add:

1.One JPanel object that can be considered as a kind of container.

2.Two JTextField objects to retrieve and hold the user’s first and the last name.

3.Four JLabel objects to display the caption for each JTextFields and the user’s full name as the Display button is clicked.

4.Three JButton objects, Display, Clear, and Exit. The Clear button is used to clean up all contents on two JTextField objects (user’s first and last name), and the Exit button is used to exit the application.

Now let’s begin to add those components one by one by dragging them from the Palette window. If you did not see the Palette window in the upper-right corner of the IDE, choose the Windows > Palette menu item to open it.

Let’s add the JPanel object first in the following operational sequence:

1.Start by selecting a JPanel from the Palette window and drop it onto the JFrame.

2.While the JPanel is highlighted, go to the Properties window and click on the ellipsis (. . .) button next to the Border property to choose a border style.

3. In the Border dialog, select TitledBorder from the list, and type in Display Full Name in the Title field, and click on the OK to save the changes and exit the dialog.

4.You should now see an empty titled JFrame that says Display Full Name JPanel object. Now add the rest of GUI-related components, including four JLabels, two JTextFields, and three JButtons, into this JPanel object as you see in Figure 5.14.

Next, let’s rename all added components and modify JLabel4 by setting the appropriate property for that label in the Properties window.

Perform the following operational sequence:

1.Double click on jLabel1 and change the text property to First Name.

2.Double click on jLabel2 and change the text to Last Name.

3.Double click on jLabel3 and change the text to Full Name.

4.Click on jLabel4 and click on the ellipsis (. . .) button next to the Border property to

choose a border style. In the Border dialog, select Line Border from the list, and change the border color to dark blue by clicking on the ellipsis (. . .) button next to the

174 Chapter 5 Introduction to NetBeans IDE

Figure 5.14. A Design Preview of the GUI Window Form.

Color property, and click on the OK to save the changes and exit the dialog. Then go to the Text property to delete the default text JLabel4 to make this an empty label.

5.Delete the sample text from jTextField1.You can make the display text editable by clicking on the Text field, pausing, and then clicking the Text field again. You may have to resize the jTextField1 to its original size. Repeat this step for jTextField2.

6.Change the name of jTextField1 to FirstTextField. To do that change, right click on the jTextField1 object and select Change Variable Name menu item from the popup

menu, then enter FirstTextField into the New Name box. Click on the OK button to complete this rename operation.

7.Perform a similar operation to change the Name property of the jTextField2 to

LastTextField, and the Name property of the jLabel4 to FullNameLabel.

8.Rename the display text of jButton1 to Display. You can edit a button’s Text property by right clicking on the button and choosing the Edit Text menu item from the popup menu. Or you can click on the button, pause, and then click again.

9.Rename the display text of jButton2 to Clear.

10.Rename the display text of jButton3 to Exit.

11.Change the Name property of the jButton1 to DisplayButton, jButton2 to ClearButton, and jButton3 to ExitButton, respectively.

Your finished GUI should now look like one that is shown in Figure 5.15.

Next, let’s develop the coding for each component to connect our GUI related components with our coding to process and response user’s input and display the running result.

5.3.2.1.3 Develop the Codes In fact, only three JButton objects need the coding process since both TextField objects are used to retrieve and hold the user’s input without any other actions in this application. A similar situation happened to the JLabel4, which is used to display the running result of this application.

In order to give function to the buttons, we have to assign an event handler to each to respond to events. In our case, we want to know when the button is pressed, either by mouse click or via keyboard. So we will use ActionListener responding to

ActionEvent.

5.3 Exploring NetBeans IDE 6.8 175

Figure 5.15. The finished GUI design window.

private void DisplayButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

FullNameLabel.setText(FirstTextField.getText() + " " + LastTextField.getText());

}

Figure 5.16. The coding for the DisplayButtonActionPerformed() event handler.

Intheearlydays,thedevelopersmustdotheconnectionbetweentheActionListener and ActionEvent manually in an application. Thanks to NetBeans IDE, this Listener and Event model has been set up and configured. To set up that connection, what the developer needs to do is just to perform a double click on the selected button. Is that easy? Yes, it is. Now let’s do this Event-Listener action connection with our first button—DisplayButton.

5.3.2.1.3.1 Coding for the Display Button: The function of the Display button is to concatenate the first and the last names entered by the user and stored in the FirstTextField and the LastTextField TextFields, and display it in the FullNameLable when this Display button is clicked by the user as the project runs.

Double clicking on the Display button, you can open its callback method or event handler, DisplayButtonActionPerformed(). Enter the codes shown in Figure 5.16 into this event handler to concatenate the first and the last names entered by the user and display it in the FullNameLabel.

Regularly, for most events and the associated event handler methods, you can do that connection by right clicking on the source object (DisplayButton in this application), and select the Events menu item from the popup menu. All events that can be triggered by this source object will be displayed in a pop-up menu. By moving your cursor to the desired event, all event handlers responding to this event will be displayed in a popup submenu, and you can select the desired event handler to open it, and a connection between that event and event handler has been set up simultaneously.

The coding for this Display button ActionPerformed() event handler is simple, and the setText() method is used to display the concatenated first and last name with a plus symbol.

176 Chapter 5 Introduction to NetBeans IDE

private void ClearButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

FirstTextField.setText(null);

LastTextField.setText(null);

FullNameLabel.setText(null);

}

Figure 5.17. The coding for the ClearButtonActionPerformed() event handler.

private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

System.exit(0);

}

Figure 5.18. The coding for the ExitButtonActionPerformed() event handler.

5.3.2.1.3.2 Coding for the Clear Button: The function of this Clear button is to clean up all contents in two TextFields, FirstTextField and LastTextField, respectively, to allow the user to enter a new name. Double click on the Clear button to open its event handler, and enter the codes shown in Figure 5.17 into this event handler.

When this button is clicked by the user, the setText() method is executed with a null as the argument to clean up three objects’ contents, the FirstTextField,

LastTextField, and FullNameLabel.

5.3.2.1.3.3 Coding for the Exit Button: The function of this button is to stop the running of this project and exit from this application. To open its event handler, this time, we use another way to do that. Perform the following operations to finish this coding process.

1. Right click on the Exit button. From the pop-up menu, choose Events > Action > ActionPerformed. Note that the menu contains many more events you can respond to! When you select the actionPerformed event, the IDE will automatically add an ActionListener to the Exit button and generate a handler method for handling the listener’s actionPerformed method.

2.The IDE will open up the Source Code window and scroll to where you implement the action you want the button to do when the button is pressed.

3.Enter the codes that are shown in Figure 5.18 into this event handler.

A system method, exit(), is executed as this button is clicked by the user, and a 0 is used as an argument to be returned to the operating system to indicate that the application has been completed successfully. A returned nonzero value indicates that some exceptions may have been encountered when the application runs.

Before we can run the project to test functions we have built, we need to do one more coding, which is to locate the GUI window in the center when the project runs.

The NetBeans IDE has a default location for each GUI window, the upper-left corner, and will display those windows in that location as the project runs. To make our GUI window located in the center of the screen as the project runs, we need to put one line

5.3 Exploring NetBeans IDE 6.8 177

public class JavaAppProjectFrame extends javax.swing.JFrame {

/** Creates new form JavaAppProjectFrame */ public JavaAppProjectFrame() {

initComponents();

this.setLocationRelativeTo(null);

// set the GUI form at the center

}

……..

}

Figure 5.19. The coding for the constructor of the class JavaAppProjectFrame.

Figure 5.20. The running result of our project.

coding into the constructor of this class since the first thing we need to do is to display our GUI window after the project runs. Open the code window by clicking on the Source button and enter one coding line into the constructor of this class, which is shown in Figure 5.19.

A system method setLocationRelativeTo() is used to set this form at the center of the screen as the project runs. A null argument means that no object can be referenced or relative to, and the JFrame Form is set to the center.

Now we have finished the building process for this project, and we are ready to run it to test functions we have built.

5.3.2.1.4 Run the Project Perform the following operations to run our project:

Click on the Clean and Build Main Project button to compile and build our project.

• Choose the Run > Run Main Project menu item.

If you get a window informing you that Project JavaAppProject does not have a main class set,then you should select JavaAppProjectPackage.JavaAppProjectFrame as the main class in the same window and click the OK button.

A sample of our running project is shown in Figure 5.20.

Enter your first and last name into the First Name and Last Name TextFields, respectively, and click on the Display button. Your full name will be displayed in the

178

Chapter 5 Introduction to NetBeans IDE

Full

Name label, as shown in Figure 5.20. Try to click on the Clear button to see what

happened. Then you can click on the Exit button to stop our project. Yes, that is all for a typical Java Application project.

A complete Java Application project JavaAppProject can be found from the folder DBProjects\Chapter 5 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

5.3.2.2 Build a Java Desktop Application

As we mentioned in the last section, a Java Desktop Application is an application based on the Swing Application Framework. Skeletons are offered for a basic desktop application and a database application that makes use of the Beans Binding and JPA libraries. By using JPA, all components developed in a relational database can be mapped to the associated objects, and developers only need to take care of those mapped objects in the entity classes to perform desired data actions with their connected databases without worrying about any real staff in the database.

Three important components are critical to develop a Java Desktop Application project:

The JPA, which helps you use Java code to interact with databases.

Beans Binding, which provides a way for different JavaBeans components to have property values that are synchronized with each other. For example, you can use beans binding to keep the values of cells in a JTable visual component in synch with the values of fields in an entity class. (In turn, the entity class represents the database table.)

The Swing Application Framework, which provides some useful building blocks for quickly creating desktop applications.

First, let’s set up a database to be used in this project.

5.3.2.2.1 Set Up the Database To simplify this database setup process and save time, we can use a default Java DB Server and a sample database that has been installed when the NetBeans IDE 6.8 is installed into your computer. Perform the following operations to complete this database setup:

• Launch the NetBeans IDE 6.8 and open the Services window.

• Right click on the Databases > Java DB node and choose Properties.

If a default Java DB server is registered, the Java DB Installation and Database Location fields will be filled in, as shown in Figure 5.21.

Click on the OK button to close this dialog box.

Now let’s start the Java DB Server in the NetBeans by right clicking on the Databases > Java DB and choose the Start Server menu item. Once the server is started, Java DB Database Process tab opens in the Output window and displays a message similar the following:

Security manager installed using the Basic server security policy. Apache Derby Network Server - 10.4.2.1 - (706043) started and ready to accept connections on port 1527 at 2010-05-24 22:38:21.187 GMT

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]