Skip to main content

Beans Binding Between Separate Forms

Posted by pkeegan on May 21, 2008 at 7:45 PM PDT

Continuing from my last post, I'll show the next steps in the creation of this simple (but not too simple) client purchase application. This time, our main focus is in creating a separate dialog which we will use for data entry. We'll need to do a few tricks so that input from the dialog is propagated to the main form and then the database.

But first we'll need to clear up a few loose ends. As I alluded to last time, I use AUTO_INCREMENT attributes for the ID columns of the CLIENTS, COUNTRIES, and ORDERS tables. This means that whenever a new row is added to those tables, that row's AUTO_INCREMENT field is given a unique value (the value of the last new record + 1). For me using AUTO_INCREMENT is a handy way to ensure having unique records.

When you generate the skeleton of the application in the New Java Desktop Application wizard, the IDE generates two entity classes (Clients.java and Orders.java) that represent database tables with the same names. However, these entity classes are missing code to deal with the AUTO_INCREMENT fields. Without that code, you will get errors when trying to enter new records. To fix that:

  1. Open the Clients.java class.
  2. Navigate to the line after the one containing @Id.
  3. Enter the line @GeneratedValue(strategy=GenerationType.IDENTITY).
  4. Press Ctrl-Shift-I to generate the necessary import statements for this annotation.
  5. Repeat the process for Orders.java.

masterdetail2-identityannotation.png

Note: You can also use code completion here. It takes three selections to get the entire line, but the import statements are generated for free.

Once you have added these annotations, you can run the application and start adding data. Click the top New button to add a client. With a client selected, click the bottom New button to add an order for that client. Click Save to push your changes to the database. Click Refresh to back out any unsaved changes.

masterdetail2-skeletonapp.png

I like tables for browsing data, but I think they leave something to be desired for data entry. So for this application, we'll add dialogs for data entry.

To create and populate the JDialog, follow these steps:

  1. Right-click the package that contains your classes and choose New | Other. Select Swing GUI Forms | JDialog Form template and name it EditClient.
  2. From the Palette window drag, drop, and arrange components for the customer's personal details.

    You should have JLabels for each of the following fields: first name, last name, address, city, state, zip code, country, and phone number. You should have JTextFields for each of those fields, except for country, for which we will use a JComboBox.

  3. Edit the display text for JLabels.
  4. Add two buttons and name them Save and Cancel.
  5. (Optional) Rename all of the components you have added to more memorable names, such as firstNameLabel. You can do this inline in the Inspector window.

The resulting layout should look something like what you see below.

masterdetail2-clientdialoglayout.png

Now we need to bind the various fields to the corresponding columns in the table. We can't bind directly to components from other forms in the Bind dialog box, so we'll have to create an intermediary property of type Clients to hold the record. When the user presses New, the property will be given the value of the currently selected record.

We can quickly generate the bean property with the IDE's bean support:

  1. At the top of the design area of the EditClient form, click the Source tab. Click somewhere within the class, such as above the variable declaration block.
  2. Press Alt-Insert (or right-click and choose Insert Code) and choose Add Property.
  3. In the Add Property dialog, name the property currentRecord, give it the type Clients, select Generate Getter and Setter, and select Generate Property Change Support.
  4. Click OK to generate the property.

masterdetail2-beanpropeditor.png

We now need to customize the generated setCurrentRecord method. Replace the body of the method with these three lines:

        Clients oldRecord = this.currentRecord;
        this.currentRecord = currentRecord;
        propertyChangeSupport.firePropertyChange("currentRecord", oldRecord, currentRecord);

Now we need to add code to the New action to open the dialog and clear the currentRecord property when a user wants to add a new record:

        JFrame mainFrame = ClientAndPurchaseApp.getApplication().getMainFrame();
        EditClient ec = new EditClient(mainFrame, false);
        ec.setCurrentRecord(c);
        ec.setVisible(true);

For now, we won't code the Save and Cancel buttons on the dialog (we've had enough digressions!). I'll cover that in an upcoming post.

With those preliminaries out of the way, we can proceed with the binding of the text fields. We'll be binding the text property of each text field to the corresponding property of the Clients object represented by currentRecord.

To bind a dialog text field to the appropriate property of currentRecord:

  1. Right-click a text field and Choose Bind | text.
  2. In the Bind dialog box, select Form as the Binding Source (note that Form is at the very bottom of the drop-down list).
  3. In the Binding Expression drop-down list, expand the currentRecord node and select the property corresponding to the text field that you are binding.
  4. Click OK to close the Bind dialog box.

masterdetail2-addressbinding.png

Do this procedure for each of the text fields in the dialog. For now, don't bind the JComboBox to anything. We'll need to do some other preparation to get that to work properly. I'll cover that in my next post.

Now you should be able to run the application, press the first New button, and enter data in the dialog. The Save and Cancel buttons on the dialog don't do anything yet, but we can save the records from the main frame. In the next post, we'll clear up some of these loose ends so that the application behaves more like applications that we are used to.

Related Topics >>

Comments

Hi, Im following through your tutorial, but I want to use JinternalFrame insted of JDialog but I get a nullpointerexception in the addPropertyChangeListener, can you help me out, I can't find out what Im doing wrong. Thanks

Patrick, thanks for the tutorial, which I've just completed. Everything worked as you said in the end. I figured out you meant:

Navigate to the newRecord() method in the Clients class and add the following code to the bottom of the method:
for "Now we need to add code to the New action"
Overall, the exercise was great. I am wondering if you could do a tutorial on sorting and filtering on the Main form? Thanks once again.

Oops, I refer to setCustomerRecord, but I really mean setCurrentRecord. So put it in the line after public void setCurrentRecord(Clients currentRecord) { I'll fix this now.

Hello Patrick, I think you have a wrong method name under "Add Property" screenshot - "setCustomerRecord" should be "setCurrentRecord". Thanks for the tutorial.

Patrick, sourced the problem
"package doesn't exist" to the following missing libraries: toplink-essentials toplink-essentials-agent mysql-connector-java-5.1.5-bin.jar These somehow didn't come in with the wizard creating the code for the application. Once I added the above libraries manually, everything worked as expected. Good work on the project

Hi Patrick, re my earlier comment, I am referring to the tutorial Input on a New Desktop Java Database Tutorial not the Binding Between Separate Forms.

Patrick, I am new to Netbeans 6.1 and Java; following through your tutorial on Binding Between Separate Forms, I encounter the following error - all the lines import javax.persistence. report package doesn't exist. In Libraries for the Project, I notice Glassfish is not included, is this significant? Would appreciate your help. John

Hello Keegan, when i add @GeneratedValue(strategy=GenerationType.IDENTITY) I get an error: SEVERE: Application class keegan.KeeganApp failed to launch javax.persistence.PersistenceException: Exception [TOPLINK-7144] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException Exception Description: SEQ_GEN_SEQUENCE: platform DatabasePlatform doesn't support NativeSequence. I'm using H2 Engine database.

hi, there is an error in the tutorial, the editClient its not a jframe , its a jDialog. good job.

Oops, I found the problem, it was my mistake for not selecting the "Generate Property Change Support". Sorry.

Hi Patrick, I was following the thru' your tutorial, and I've generated the bean property using Netbeans 6.1, and I've copy and pasted the codes for the setCurrentRecord method in the EditClient.java. But Netbean high-lighted an error saying that "cannot find symbol variable propertyChangeSupport". I tried Ctrl-Shift-I to fix imports, but to no avail. What could be the cause? Thank you very much in advance for your kind assistance.

Patrick, In your tutorial "Binding JComboBox's Elements and Selected Item" you mention Enter values into the various text fields and choose a country from the combo box. Notice that the values that you enter in the dialog box also appear in the top table in the main form , including the country you selected from the combo box. I don't see what I enter in the Editclient form echoed in the main form, but I'll work through to number four and let you know.

I'm not sure where to place : Clients oldRecord = this.currentRecord; this.currentRecord = currentRecord; propertyChangeSupport.firePropertyChange("currentRecord", oldRecord, currentRecord);
Now we need to add code to the New action (?)to open the dialog and clear the currentRecord property when a user wants to add a new record: JFrame mainFrame = ClientAndPurchaseApp.getApplication().getMainFrame(); EditClient ec = new EditClient(mainFrame, false); ec.setCurrentRecord(c); ec.setVisible(true);

How does it fail? What happens? BTW, have you continued through the end of this series of tutorials? The actual synchronization of the dialog and the form don't happen until the last blog in this series

Patrick, thanks for that response. As I mentioned I'm new to Java. Finding your tutorial very helpful. Can't say what happened, you're probably right about missing the Java Desktop Application project template as I was skipping the database setup you are using and was using one of my own. Thanks for the line on the c variable. Just figured it out. Have one more question if I may? I appreciate your patience, but I can't seem to get the EditClient form to synchronise with the main form. Am I misunderstanding something here in the tutorial: "We now need to customize the generated setCustomerRecord method. Replace the body of the method with these three lines:" Regards and thanks

Hi jdross, regarding the missing libs, did you start with the Java Desktop Application project template (from the previous blog entry)? Regarding, the c, c is an instance variable for the new record. It is declared in the first line of the newRecord() method: clientpurchaseapp.Clients c = new clientpurchaseapp.Clients();

Patrick, can you explain the reference to c in ? ec.setCurrentRecord(c); as it's not clear to me where the variable is declared