站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Connecting a GUI to a Derby Database with NetBeans IDE

Connecting a GUI to a Derby Database with NetBeans IDE

摘要: Contributed by Talley Mulligan This tutorial guides you through the process of connecting the GUI of an application called ContactEditor to a Derby database. In the process you will add data aware JDBC components to the GUI that will enable the program to interact with an employee database
Contributed by Talley Mulligan

This tutorial guides you through the process of connecting the GUI of an application called ContactEditor to a Derby database. In the process you will add data aware JDBC components to the GUI that will enable the program to interact with an employee database.

In this tutorial you will learn how to:

Note that this tutorial refers to a sample project called GUI DB Exercise Initial which you should refer to while working through the steps. You can download the zip archive here. Also note that the archive includes a GUI DB Exercise Final project showing the completed application.


Getting Started


In the GUI Builder Quickstart tutorial, we concentrated on building a dialog called ContactEditorUI for the ContactEditorUI.java application. In this tutorial, we'll connect both the ContactEditorUI GUI form we created before and the main (parent) window of the application's UI to a Derby database. Note that though the tutorial images illustrate the process on Macintosh OS-X, the steps are virtually identical for other supported platforms, such as Windows or Solaris.

In order to successfully accomplish this tutorial, you must already have the IDE's included Derby database server set up and running. Note that as of NetBeans IDE 5.5 Beta, the included database is no longer called Derby and is referred to as Java DB. You also need to compile the necessary support classes that were included in the sample project (visible in the Projects window) into the project. For more information about installing and configuring Derby for use with NetBeans, see the NetBeans Derby tutorial.

Finally, you also must have already created the contact_database with both User Name and Password set to nbuser. You also must have added the necessary fields to the database using the Create Table UI or by executing the following SQL statement:


CREATE TABLE "CONTACTS" ( "ID" INTEGER not null primary key, "FIRST_NAME" VARCHAR(50), "LAST_NAME" VARCHAR(50), "TITLE" VARCHAR(50), "NICKNAME" VARCHAR(50), "DISPLAY_FORMAT" SMALLINT, "MAIL_FORMAT" SMALLINT, "EMAIL_ADDRESSES" VARCHAR(1000) )

Note that if you created the table using the SQL command instead of the Create Table UI, you need to refresh the Tables node in the Runtime window in order to see the Contacts table.


Note: In order to complete this tutorial successfully, you must be running NetBeans IDE 5.0 on JDK 5.


Adding the Data Model


Since the application's main window GUI has already been laid out for us, we can jump straight to adding the data-aware components that will enable us to interact with our data in the database. In this section, we'll add the data model that will ensure the data is presented to the UI in the correct form.
Adding a JDBCRowSet

Because the JDBCRowSet we require is already included in the GUI DB Example project, we only need to add it to our application GUI. Since the included RowSets have BeanInfos, we can use them as we would other components with the IDE displaying their properties in the Properties window. Because we're only going to use this class once, we don't need to bother installing the JDBCRowSet into the Palette in order to add it to the form. While this approach is worthwhile if you want to use a class repeatedly, we'll simply copy and paste to save time and hassle.

To add a JDBCRowSet to the form:

  1. In the Projects window, right-click the JDBCRowSet.java node and choose Copy from the pop-up menu.

  2. Paste it anywhere in the Design Area.

    The IDE adds the JDBCRowSet to the form and a node representing the row set appears in the Inspector window.

Notice that the Inspector window node is added within the Other Components node. If you receive an error when attempting to paste the row set, compile the project and then try again.

Setting the JDBCRowSet's Properties

Now we need to edit the JDBCRowSet properties so that it refers to the Contacts database we created earlier. We also need to set the driver and path it should use, as well as provide the password and username it will need to make the connection.

To edit the JDBCRowSet's properties:

  1. Select the JDBCRowSet1 node in the Inspector window (not the Projects window).

  2. In the Properties window, enter select * from contacts for the command property.

  3. Enter org.apache.derby.jdbc.ClientDriver for the driver property.

  4. Enter jdbc:derby://localhost:1527/contact_database for the url property.

  5. Enter nbuser for the password property.

  6. Enter nbuser for the username property.
Adding the Data Model

Now we need to add the data model that will be the layer between the application and our database as well as encapsulate data access, providing the logic for accessing and modifying the data itself. Once again, the necessary ContactsModel class has been provided in the example project so we'll need only add it to our application. Including such a class enables the possibility of changing the data model without necessitating changes to the GUI.

To add the data model to the form:

  1. In the Projects window, right-click the ContactsModel.java node and choose Copy from the pop-up menu.

  2. Paste it anywhere in the Design Area.

    The IDE adds the ContactModel to the form and a node representing the row set appears within the Other Components node in the Inspector window.

To change the variable name of the data model:

  1. Right-click the contactsModel1 node in the Inspector window and choose Change Variable Name from the pop-up menu.

  2. In the Rename dialog that appears, enter contactsModel for the new variable name and click OK.

To set the rowSet property of the data model:

  1. Select the contactsModel node in the Inspector window.

  2. In the Properties window, click the ellipsis button (...) for the rowSet property.

  3. In the editor that appears, select the Bean radiobutton in the Get Parameter From pane.

  4. Select jDBCRowSet1 from in the Select Bean combobox.

  5. Click OK to exit the dialog.

    The IDE sets form's contactsModel data model to use the jDBCRowSet.

top


Binding the Database to the UI


In order for our GUI to interact with the contact information stored in our database, it's necessary to bind the data to the components that will display and permit users to interact with it. In this section, we'll start connecting our GUI to the JDBC components that will enable interaction with the database.

Setting the JTable RowSet Model

In order for our GUI's JTable to display the contact data properly, we need to set it to use the provided RowSetTableModel class. We also need to point the RowSetTableModel to the JDBCRowSet we added earlier so that it will be able to forward column information and data to the JTable itself. Finally, we'll edit the rowSetTableModel1 instance so that only those columns which we want to display will be visible in the GUI's main window.

To add a RowSetTableModel to the form:

  1. In the Projects window, right-click the RowSetTableModel.java node and choose Copy from the pop-up menu.

  2. Paste it anywhere in the Design Area.

To set the rowSet property of the table model:

  1. In the Inspector, select the rowSetTableModel1 node.

  2. In the Properties window, open the rowSet property editor by clicking its ellipsis button (...).

  3. Select the Bean radiobutton in the Get Parameter From pane.

  4. Select jDBCRowSet1 from in the Select Bean combobox.

  5. Click OK to exit the dialog.

To set the model property of the JTable:

  1. Select the JTable in the Inspector. Note that when you select the JTable in the form, the JScrollPane component is highlighted in the Inspector and its properties are available for editing in the Properties window (not the JTable's properties).

  2. In the Properties window, open the editor for the model property by clicking its ellipsis button (...).

  3. In the model editor that appears, choose Form Connection in the Select Mode combobox.

  4. Select the Bean radiobutton and choose rowSetTableModel1 in the Component combobox.

  5. Click OK to close the editor.

In order to determine which table columns will be visible at runtime, we need to set them explicitly. In order to do this, we need to adjust the rowSetTableModel1's properties.

To set the visibility of the table columns:

  1. In the Inspector, select the rowSetTableModel1 node.

  2. In the Properties window, open the visibleColumns property editor by clicking its ellipsis button (...).

  3. In the editor that appears, enter the following column names in the Item field one at a time and click Add.

    • NICKNAME
    • FIRST_NAME
    • LAST_NAME

  4. Click OK to exit the dialog.

    The IDE sets the form's JTable to display the specified columns and the column titles appear in the form itself in the order in which they were added.

Setting Main Window Close Behavior

In order to release the various resources held in the model when application windows are closed, we also need to specify the desired behavior explicitly. In this section we'll set the event actions that control this behavior for both the application's main window and the details dialog.

To edit event actions for the main window Close button:

  1. Right-click the Close button and choose Events > Action > actionPerformed.

  2. In the Source Editor, select the line where the cursor is located (it should read //TODO add your handling code here) add the following code in the body of the editContactActionPerformed method:

    contactsModel.dispose(); // releases resources held by the model (like DB connection) System.exit(0); // exists the application
  3. Click the Design button to return to the GUI Builder.

To edit event actions for the main window:

  1. Right-click the JFrame container in the Inspector and choose Events > Window >windowClosing.

  2. In the Source Editor, select the line where the cursor is located. Then add the following code:

    contactsModel.dispose(); // releases resources held by the model (like DB connection) System.exit(0); // exists the application
  3. Again, click the Design button to return to the GUI Builder.
Adding Button Event Handlers

In order for the main window's various buttons to result in the desired behavior, the actions have to be set on them. In this section we'll do just that by defining the event handlers necessary for them to trigger the appropriate events.

To add an event handler to the Edit button:

  1. Right-click the Edit button and choose Events > Action > actionPerformed.

  2. In the Source Editor, select the line where the cursor is located and add the following code:

    showDetailDialog(false);

  3. Add the following method into the code in the body of the contactEditor class (on or about line 346).

    private void showDetailDialog(boolean inserting) { contactsModel.setInsertMode(inserting); firstNameField.setText(contactsModel.getFirstName()); lastNameField.setText(contactsModel.getLastName()); titleField.setText(contactsModel.getTitle()); nicknameField.setText(contactsModel.getNickname()); displayFormat.setSelectedIndex(contactsModel.getDisplayFormat()); emailField.setText(""); switch (contactsModel.getMailFormat()) { case 0: htmlChoice.setSelected(true); break; case 1: plainTextChoice.setSelected(true); break; case 2: customChoice.setSelected(true); break; } javax.swing.DefaultListModel listModel = new javax.swing.DefaultListModel(); Object[] mails = contactsModel.getEmails(); for (int i=0; i<mails.length; i++) listModel.addElement(mails[i]); emailsList.setModel(listModel); details.pack(); details.setVisible(true); }

    The IDE adds the listener to the Edit button enabling the button to interact with the contactsModel and database whenever clicked, as shown in the following illustration.


Setting the Event Handlers


To add an event handler for the Add button:

  1. Right-click the Add button and choose Events > Action > actionPerformed.

  2. In the Source Editor, select the line where the cursor is located and add the following code:

    showDetailDialog(true);

To add an event handler for the Remove button:

  1. Right-click the Remove button and choose Events > Action > actionPerformed.

  2. In the Source Editor, select the line where the cursor is located and add the following code:

    contactsModel.removeContact();
Setting the Table Selection Model

Now it's time to set the table selection model that will listen for property changes in the model and determine if the selected contact can be edited or not. Note that for the purposes of the tutorial, the ContactsModel implementation permits any selected contact to be edited or removed.

To set the selection model for the table:

  1. In the Inspector window, expand the JScrollPane1 node and select the JTable.

  2. In the Properties window, click the ellipsis button for selectionModel property.

  3. In the editor that appears, select the Property radiobutton and click the ellipsis button.

  4. In the Select Property dialog that opens, choose contactsModel in the combobox. Then select contactSelection in the Properties pane.

  5. Click OK to exit the dialogs.

To connect contactsModel with the Edit and Remove buttons:

  1. Right-click the Edit button in the Design Area and choose Events > PropertyChange > propertyChange from the pop-up menu.

  2. In the Source Editor, copy and paste the following code on the line where the cursor is positioned.

    editContact.setEnabled(contactsModel.isEditingEnabled());

  3. Repeat the procedure for the Remove button, but this time use the following code:

    removeContact.setEnabled(contactsModel.isRemovalEnabled());

    The IDE sets the buttons to enable editing and removal of the database contacts.

top


Creating the Application Logic


Though we've now managed to bind our database to our GUI using the provided JDBC components, we still need to set up the various events that will be fired when users click buttons or manipulate other GUI components. In this section, we'll focus on creating the application logic that will control how the various Swing components that make up our GUI will interact with the database.

Changing GUI Builder Focus

Now that we've completed the necessary modifications to the top-level Contacts container that will be our application's main window, we need to shift the GUI Builder's focus to the details dialog in order to complete the process of binding the database to our GUI.

To change the GUI Builder's focus:

  1. In the Inspector window, right-click the details dialog's node and choose Design This Container from the pop-up menu. Note that you can also simply double-click the node to accomplish this.

  2. The IDE shifts focus to the nested details JDialog container.


Changing GUI Builder Focus, Before and After


Setting Button Actions

Because buttons are our interface's primary means of interacting with the data contained in our database, we'll start by setting the events they will fire in the course of interacting with the database.

To edit event actions for the Add button:

  1. Right-click the Add button and select Events > Action > actionPerformed.

  2. In the Source Editor, paste the following code at the insertion point:

    ((javax.swing.DefaultListModel)emailsList.getModel()).addElement(emailField.getText());

    The IDE sets the Add button to get the list of email addresses when it is clicked.

To edit event actions for the Edit button:

  1. Right-click the Edit button and select Events > Action > actionPerformed.

  2. In the Source Editor, paste the following code at the insertion point:

    ((javax.swing.DefaultListModel)emailsList.getModel()).setElementAt(emailField.getText(), emailsList.getSelectedIndex());

    The IDE sets the Edit button to set the list of email addresses whenever clicked.

To edit event actions for the Remove button:

  1. Right-click the Remove button and select Events > Action > actionPerformed.

  2. In the Source Editor, paste the following code at the insertion point.

    ((javax.swing.DefaultListModel)emailsList.getModel()).removeElementAt(emailsList.getSelectedIndex());

    The IDE sets the Remove button to remove the selected email address when clicked.

Defining the JList Event Listener

Now we need to add an event listener that will watch for changes to the database. Though the JList is located within the Details dialog, we can set the component's event listener without switching the GUI Builder's focus by using the Inspector window.

To set the JList's event listener:

  1. Right-click the emailsList JList and select Events > ListSelection > valueChanged.

  2. In the Source Editor, paste the following code at the insertion point:

    editEmail.setEnabled(emailsList.getSelectedIndex() != -1); removeEmail.setEnabled(emailsList.getSelectedIndex() != -1); emailField.setText((String)emailsList.getSelectedValue());

    The IDE sets the JList's event listener to watch for changes to the database data.

Editing Events with the Connection Wizard

So far we've been relying on copying and pasting to set up our program's application logic, but the IDE also includes a tool designed to assist in this common task. In this section we'll use the GUI Builder's Connection Wizard to set the Contact Details Cancel button to close the dialog, discarding any changes that have been made.

To edit event actions for the Cancel button:

  1. Click the Connection Wizard button in the GUI Builder's toolbar.

  2. Select the Cancel button and then the Contact Details JFrame container. Confirm that cancelButton is specified as the Source Component in the Connection wizard that appears.

  3. Select action > actionPerformed in the Select Source Event pane and click Next.

  4. Confirm that details is specified as the Source Component in the Connection wizard.

  5. On the Specify Target Operation page of the wizard, select the Method Call radiobutton and choose setVisible(boolean) from the list of properties. Click Next.
  6. On the Enter Parameters wizard page, select the Value radiobutton and enter false. Click Finish.

    The IDE's Connection Wizard sets the dialog's Cancel button to exit the dialog whenever clicked.

To edit event actions for the OK button:

  1. Right-click the OK button and select Events > Action > actionPerformed.

  2. In the Source Editor, paste the following code at the insertion point:

    contactsModel.updateContact(firstNameField.getText(), lastNameField.getText(), titleField.getText(), nicknameField.getText(), displayFormat.getSelectedIndex(), htmlChoice.isSelected() ? 0 : (plainTextChoice.isSelected() ? 1 : 2), ((javax.swing.DefaultListModel)emailsList.getModel()).toArray()); details.setVisible(false);

top


Finishing Up


Now that we've managed to rough out our ContactEditor application's GUI, we'll take a look at the results of our handywork.
Previewing the GUI

Now that we've integrated the details dialog with the main Contacts Application window and connected them to our Contacts database, we can preview the UI to see if everything looks right prior to building and running. Notice that even though we left the details dialog as the container that had focus in the IDE's Design Area, the application's main window appears when clicking the Preview button.

To preview the GUI:

  1. Click the Preview button in the GUI Builder's toolbar.

    The IDE opens the GUI's top level container in its own window, enabling you to test the form's appearance and resizing behavior.


Previewing the GUI


You may have noticed over the course of the tutorial that though the main window JFrame's title property is set to Contacts, no title has been visible in the GUI Builder's Design Area. This is because titlebars are rendered dynamically at runtime so you'll need to click the Preview Form button if you want to see the results of title property edits.

Testing Database Functionality

Now that we've verified that our GUI looks like it should, we'll test our application to verify that it works as we expect it to. While the preview feature is helpful for identifying issues with visual aspects of our GUI (alignments, resizeability behavior, and so forth), we have to build and run the application if we want to view any nested windows included in our GUI or test the business logic.

To build and run the application:

  1. Right-click the project node in the Projects window and choose Run Project. Alternately, you can click the Run Main Project button in the GUI Builder's toolbar.
  2. The IDE builds the application, reporting the status and any problems encountered in the Output window. Once the build succeeds, the IDE launches the application and the GUI's main window appears.

Now that the application is running, you can further test the GUI as well as put its various interactions with the database itself through the paces by adding the names of your friends and family as shown in the following image.


The Completed Contact Editor Application


top


Next Steps

You have now completed the IDE's GUI Building tutorial. For more information on working with Java GUI's in the NetBeans IDE, see:

top


↑返回目录
前一篇: Comparing Java EE 5 Platform and J2EE 1.4 Platform
后一篇: Consuming Web Services in NetBeans IDE 4.1(1)