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

当前页面: 开发资料首页Netbeans 专题使用 NetBeans IDE 将 GUI 连接到 Derby 数据库(2)

使用 NetBeans IDE 将 GUI 连接到 Derby 数据库(2)

摘要: 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.

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


↑返回目录
前一篇: Wireless Connection Wizard
后一篇: 使用 NetBeans IDE 将 GUI 连接到 Derby 数据库(1)