< NetBeans & Java Desktop GUI 2 | Java & Friends | Recap: NetBeans & MySQL Database >


 

 

NetBeans, Java Desktop GUI and Java DB (Derby):

Combining All Together

 

 

 

Contents:

  1. Pre requirement

  2. Setting Up the Database

  3. To manually register Java DB in the IDE

  4. Starting the Server and Creating a Database

  5. To start the database server

  6. To create the database

  7. Connecting to the Database

  8. Creating the Application

  9. Running the Generated Application

  10. Reviewing the Generated Parts of the Application

  11. Adding More Controls

  12. Follow these steps to add the additional components

  13. Binding Controls to Values in the Table

  14. To bind the sliders to their corresponding table elements:

  15. To bind the checkboxes to their corresponding table elements

  16. To verify that the sliders and checkboxes work

  17. Setting up a Custom Component

  18. To make the CarPreview component available for the CarsApp project

  19. To add the CarPreview component to the application

 

The machine specifications used in this task are:

  • Intel Pentium Core 2 Duo, 2.2 GHz,

  • Windows XP Pro SP2 + periodical patches + periodical updates.

  • 2 GB DDR2 RAM

  • 160 GB SATA HDD

  • 17” SyncMaster 713N monitor.

Pre requirement

 

For this tutorial you need to have the following software installed on your computer:

 

 

This tutorial shows how to create a desktop Java application through which you can access and update a database. The tutorial takes advantage of support in NetBeans IDE 6.0 for the following technologies:

 

 

We will create a database CRUD (create, read, update, delete) application with a custom component used for visualizing the data (car design preview).

 

Setting Up the Database

 

Before you begin creating a desktop CRUD (create, read, update, delete) application in the IDE, you should already have the IDE connected to the database that your application will use. Having this connection set up in advance will allow you to take advantage of IDE features that automate the binding of the database to your application.

In this tutorial, we provide instructions for using a Java DB database, since there is a convenient interface for starting and stop the Java DB database server from the IDE. However, you can use a different database server without too much difficulty.

First check to see if you have Java DB registered in the IDE. Java DB is automatically registered in the IDE in a number of cases, such as when you have Sun Java System Application Server registered in the IDE or when you are running on JDK 6.

 

To determine if Java DB is registered in the IDE:

 

 

 

If the Settings menu item is the only item that is not grayed out, you need to manually register Java DB in the IDE.

 

To manually register Java DB in the IDE

 

  1. Choose Tools > Java DB Database > Settings.

  2. In the Java DB Installation field, enter the path to the database server.

  3. In the Database Location property, enter the folder where you want the databases to be stored.

  4. Click OK.

 

 

Starting the Server and Creating a Database

 

Once Java DB is registered with the IDE, you can easily start and stop the database server, as well as create a new database.

 

To start the database server

 

 

 

If you do not already have a location set for the database, the Set Database Location dialog box appears. Enter a location for the database server to store the databases. You can create a new folder there if you wish.

Once the server is started, Java DB Database Process tab opens in the Output window and displays a message similar to the following in the Output window at the bottom of the NetBeans IDE:

 

Apache Derby Network Server - 10.2.2.0 - (485682) started and ready to accept connections on port 1527 at 2008-02-05 08:09:07.015 GMT

 

To create the database

 

  1. Choose Tools > Java DB Database > Create Database. The Create Java DB Database dialog opens.

 

 

  1. For the Database Name text field, type car_database. Also set the User Name and Password to nbuser.

  2. Click OK.

 

 

Connecting to the Database

 

So far, we have successfully started the database server and created a database. However, we still need to connect to the new database before we can start working with it in the IDE. To connect to the car_database database:

 

  1. Switch to the Services window (Ctrl+5) and expand the Databases node to see your new database.

 

 

  1. Right-click the database connection node (jdbc:derby://localhost:1527/car_database[nbuser on NBUSER]) and choose Connect.

 

 

The connection node icon should now appear whole (connection node icon), which signifies that the connection was successful.

 

 

  1. Expand the connection node, right-click its Tables subnode, and choose Execute Command.

 

 

  1. Copy the contents of the car.sql (shown below) file and paste them into the SQL Command 1 tab of the Source Editor. Keep in mind that the SQL script must be unformatted text file. If you copy from formatted text editor such as Word, you need to paste it in the unformatted text editor such as WordPad or Notepad and re-copy it.

 

create table "CAR"

(

  "MAKE" VARCHAR(50) not null primary key,

  "MODEL" VARCHAR(50),

  "PRICE" INTEGER,

  "BODY_STYLE" VARCHAR(30),

  "COLOR" VARCHAR(20),

  "SUN_ROOF" INTEGER default 0,

  "SPOILER" INTEGER default 0,

  "TIRE_SIZE" INTEGER,

  "TIRE_TYPE" INTEGER,

  "MODERNNESS" INTEGER

);

insert into car values ('Acura', 'NSX', 47075, 'coupe', 'yellow', 1, 1, 18, 1, 38);

insert into car values ('Audi', 'A8', 63890, 'sedan', 'black', 1, 0, 24, 0, 88);

insert into car values ('BMW', 'M-Series', 108900, 'coupe', 'red', 1, 0, 50, 0, 44);

insert into car values ('Buick', 'Lucerne', 31599, 'sedan', 'black', 1, 0, 26, 2, 65);

insert into car values ('Cadilac', 'XLR', 62777, 'convertible', 'green', 0, 0, 14, 1, 26);

insert into car values ('Chevrolet', 'Corvette', 74999, 'coupe', 'yellow', 0, 0, 53, 2, 44);

insert into car values ('Chrysler', 'Sebring', 89595, 'convertible', 'silver', 1, 1, 63, 0, 49);

insert into car values ('Daewoo', 'Leganza', 10590, 'sedan', 'blue', 1, 0, 47, 1, 66);

insert into car values ('Dodge', 'Ram 2500', 38825, 'pickup', 'white', 0, 1, 96, 1, 82);

insert into car values ('Eagle', 'Talon', 5995, 'hatchback', 'silver', 1, 1, 42, 1, 53);

insert into car values ('Ford', 'F250', 47440, 'pickup', 'orange', 0, 1, 46, 1, 57);

insert into car values ('Geo', 'Metro LSI', 3495, 'convertible', 'green', 0, 1, 54, 0, 74);

insert into car values ('GMC', 'Yukon XL Denali', 46355, 'wagon', 'gray', 0, 1, 63, 1, 45);

insert into car values ('Honda', 'Odyssey', 34895, 'coupe', 'white', 1, 1, 11, 2, 68);

insert into car values ('Hummer', 'H1', 119999, 'sedan', 'red', 1, 1, 39, 0, 17);

insert into car values ('Hyundai', 'Azera', 27950, 'sedan', 'silver', 1, 1, 13, 0, 18);

insert into car values ('Infiniti', 'QX56', 44995, 'wagon', 'green', 0, 0, 15, 2, 75);

insert into car values ('Isuzu', 'Hombre', 30545, 'wagon', 'white', 1, 0, 16, 2, 55);

insert into car values ('Jaguar', 'XK', 91675, 'convertible', 'brown', 1, 1, 17, 2, 31);

insert into car values ('Jeep', 'Commander', 37497, 'wagon', 'silver', 1, 1, 54, 0, 96);

insert into car values ('Kia', 'Amanti', 25988, 'sedan', 'gray', 1, 1, 62, 0, 100);

insert into car values ('Land Rover', 'Range Rover', 89350, 'wagon', 'black', 0, 1, 71, 0, 63);

insert into car values ('Lexus', 'SC 430', 61321, 'convertible', 'yellow', 1, 1, 81, 0, 98);

insert into car values ('Lincoln', 'Navigator', 42500, 'wagon', 'blue', 1, 1, 46, 0, 85);

insert into car values ('Mazda', 'CX-7', 27988, 'wagon', 'brown', 1, 0, 28, 0, 40);

insert into car values ('Mercedes-Benz', 'CLS Class', 86900, 'sedan', 'black', 0, 1, 99, 1, 46);

insert into car values ('Mercury', 'Mariner', 30995, 'wagon', 'red', 0, 0, 59, 2, 41);

insert into car values ('MINI', 'Cooper', 32930, 'convertible', 'silver', 0, 0, 78, 1, 98);

insert into car values ('Mitsubishi', 'Eclipse', 31995, 'convertible', 'red', 0, 0, 83, 1, 48);

insert into car values ('Nissan', 'Armada', 36777, 'wagon', 'blue', 0, 1, 11, 1, 60);

insert into car values ('Oldsmobile', 'Silhouette', 17500, 'wagon', 'blue', 1, 1, 79, 1, 27);

insert into car values ('Plymouth', 'Voyager', 9995, 'wagon', 'white', 1, 1, 37, 1, 13);

insert into car values ('Pontiac', 'Firebird', 39999, 'hatchback', 'red', 0, 0, 13, 0, 18);

insert into car values ('Porche', '911 Carrera', 399999, 'coupe', 'silver', 1, 0, 18, 2, 58);

insert into car values ('Saab', '9-3', 35999, 'convertible', 'green', 1, 1, 16, 0, 13);

insert into car values ('Saturn', 'Sky', 27499, 'convertible', 'silver', 1, 1, 25, 0, 86);

insert into car values ('Scion', 'tC', 21530, 'sedan', 'red', 0, 0, 92, 1, 37);

insert into car values ('Subaru', 'B9 Tribeca', 34999, 'wagon', 'green', 0, 1, 98, 0, 88);

insert into car values ('Suzuki', 'XL-7', 25880, 'wagon', 'brown', 1, 0, 83, 1, 16);

insert into car values ('Toytota', 'MR2 Spyder', 99999, 'convertible', 'silver', 0, 0, 21, 2, 99);

insert into car values ('Volkswagen', 'Touareg', 51274, 'wagon', 'black', 1, 0, 91, 0, 48);

insert into car values ('Volvo', 'XC90', 45845, 'wagon', 'gray', 0, 0, 31, 2, 32);

 

 

This is the SQL script which will populate the database with data about cars.

 

  1. Click the Run SQL button (Run SQL button) in the toolbar of the Source Editor to run the script. You can see the report in the Output windows at the bottom. Make sure there is no error, else you need to correct it and re-execute the script.

 

 

Creating the Application

 

  1. Choose Project > New Project.

 

 

  1. In the first panel of the wizard, expand the Java category and select the Java Desktop Application template. Click Next.

 

 

The Java Desktop Application template provides many basics of a visual application, including basic menu items and commands.

 

  1. In the Name and Location page of the wizard, do the following things:

  1. In the Project Name field, type CarsApp. The value of this field sets the display name for the project in the Projects window.

  2. Optionally, edit the Project Location field to change the location of your project metadata.

  3. In the Choose Application Shell field, select Database Application.

  4. Click Next.

 

 

  1. In the Master Table page of the wizard, select the database connection for the CAR database. The listing for the database should look something like the following and click Next button.

 

jdbc:derby://localhost:1527/car_database[nbuser on NBUSER]

 

 

After the connection to the database is established, the Database Table field should display CAR and the Columns to Include list should include the names of 10 columns for the CAR database. For now, we will use only five of them in the application.

  1. Select the bottom five column names (beginning with SUN_ROOF and ending with MODERNNESS) and click the < button to move them to the left column. Click Next.

 

 

  1. In the Detail Options panel, click Finish.

 

 

The wizard then generates a basic user interface with a table and a database connection. This might take a few seconds as the IDE generates the project and the code.

 

 

 

Running the Generated Application

 

At this point, you have a basic running application with a graphical user interface (GUI) that has the following features:

 

 

 

To see some of the features that are already built into the application, follow these steps:

 

  1. Right-click the project's node and choose Run. After a few seconds, the application stars and a window called Database Application Example appears. This window contains a table and several controls that enable you to edit the CARS database.

 

 

  1. Select the first record in the table (for the Acura).

  2. Select the Price text field and replace the existing value with 46999. Then press Enter.  The value should appear updated in the table. (However, that value will not be reflected in the database until you click Save.) Similarly, you can update any other values in the table.

 

 

  1. Click New button to create a new record. Then fill in values for each of the fields (Make, Model, Price, Body Style, and Color). For example, you can fill in Trabant, Classic, 1000, wagon, and blue. Click Save to save the entry in the database.

 

 

  1. Click the Database Application Example title bar and drag the application to a different place on your screen.

  2. Click the left border of the Database Application Example window and drag to the left to increase the size of the window.

 

 

  1. In the Database Application Example menu bar, choose File > Exit.

  2. In the IDE, right-click the project's node and choose Run Project. The Database Application Example window will open in the same size and position it was in when you closed the application.

 

Reviewing the Generated Parts of the Application

 

The connection between the master table (a JTable component) and the database is handled with a combination of the following mechanisms, all of which have been generated by the IDE:

 

  1. The Car.java entity class, which is used to read and write data to the CAR database table. Entity classes are a special type of class that enables you to interact with databases through Java code. Entity classes use Java annotations to map class fields to database columns.

  2. The META-INF/persistence.xml file, which defines a connection between the database and the entity class. This file is also known as the persistence unit.

  3. Using beans binding to connect the properties of the entity class with the properties of the JTable component. Beans binding is a new technology based on JSR 295 and which included in the latest Java SE release.

  4. The entityManager, query, and list objects, which are defined in the CarsAppFrame class and which are listed in the Inspector window.

Using the Inspector window and the property sheet, you can follow these steps to see how the JTable is bound to data:

 

  1. In the Inspector window, select the mainPanel[JPanel] > masterScrollPane [ScrollPane] > masterTable [JTable] node. Then click the Binding tab in the Properties window.

 

 

 

  1. Look at the elements property to confirm that it is bound to a list.

  2. Click the ellipsis [...] button to open the Bind masterTable.elements customizer, where you can further customize the binding between the table and the database. For example, you can see that the customizer enables you to specify which table columns are bound. Make sure you click the Cancel button instead of OK button when closing this sheet else the element will be unbind because there is no column in the Selected field on the right. However you can re-bind it anytime later.

 

 

Besides the Binding category in property sheet you can also use the Bind menu in context menu.

 

Adding More Controls

 

We will now add controls to the form for some of the attributes we initially excluded. Instead of using a table, we will add JSlider components (for the tire size and modernness attributes) and JCheckbox components (for the sun roof and the spoiler).

 

Follow these steps to add the additional components

 

  1. Add the first slider by clicking the Slider button in the Palette window and then clicking in the form just above the New button. Before clicking in the form to insert the slider, make sure that no horizontal slotted guiding lines are shown. These lines indicate that the slider will be inserted in the same line as the fields or the buttons. See the figure below to see where you should drop the slider into the form. Note: If you drop the component in a place you do not want and thus cause several undesired layout changes, you can use the Undo command to reverse the changes. Choose Edit > Undo or press Ctrl-Z.

 

 

 

 

  1. If necessary, stretch the slider to the left to align it with the left side of the text field components.

  2. Stretch the slider to the right to span the whole form width.

 

 

 

  1. Add a label to the left of the slider and set its text to Tire Size. (Click the label to make it editable.)

 

 

  1. Add another slider below the first slider, and adjust its width and alignment where necessary.

  2. Add another label below the Tire Size label and set its text to Modernness.

 

 

  1. Add two checkboxes below the sliders. Set their text to Spoiler and Sun Roof. (Make the display text editable by clicking the checkbox once, pausing, and then clicking the checkbox again. You can also right-click the checkbox and choose Edit Text.)

 

 

 

 

By clicking the Preview Design () the form should look like the screenshot shown below.

 

 

When we run as done previously, the following is the GUI.

 

 

Binding Controls to Values in the Table

 

We will now use beans binding features to tie the values shown in table cells to the state of the controls we have added. This will allow you to change the values of cells in the table by using the sliders and checkboxes.

 

To bind the sliders to their corresponding table elements

 

  1. Back to the Design view, in the form, right-click the Tire Size slider and choose Bind > value.

 

 

  1. In the Binding Source drop-down list of the Binding dialog box, select masterTable.

 

 

  1. In the Binding Expression drop-down list, select the selectedElement > tiresize node.

 

 

In the Binding sheet you can see the value field has been filled with the binding value.

 

 

  1. In the form, right-click the Modernness slider and choose Bind > value.

 

 

  1. In the Binding Source drop-down list of the Binding dialog box, select masterTable.

 

 

  1. In the Binding Expression drop-down list, select selectedElement > modernness.

 

-------------------------------------------------------------------------------------------------------------------------------

 

--------------------------------------------------------------------------------------------------------------------------------

 

To bind the checkboxes to their corresponding table elements

 

  1. In the form, right-click the Spoiler checkbox and choose Bind > selected.

 

 

  1. In the Binding Source drop-down list of the Binding dialog box, select masterTable.

 

 

  1. In the Binding Expression drop-down list, select selectedElement > spoiler.

  2. Click OK to exit the Bind dialog box.

 

 

 

  1. In the form, right-click the Sun Roof checkbox and choose Bind > selected.

 

 

  1. In the Binding Source drop-down list of the Binding dialog box, select masterTable.

 

 

  1. In the Binding Expression drop-down list, select selectedElement > sunRoof.

  2. Click OK.

 

 

You should now be able to change database entries using the slider and checkboxes.

 

To verify that the sliders and checkboxes work

 

  1. Open the Services window.

  2. Make sure the IDE has a connection to the database by right-clicking Databases > jdbc:derby;//localhost:1527/car_database and choosing Connect.

 

 

  1. Right-click the Databases > jdbc:derby;//localhost:1527/car_database > Tables > CAR node and choose View Data.

 

 

  1. Look at the SUN_ROOF, SPOILER, TIRE_SIZE, and MODERNNESS values for the first record.

 

 

  1. Choose Run > Run Main Project to execute the application.

 

 

  1. Select CarApp and click OK button.

 

 

The running application should look similar to the screenshot shown below.

 

 

  1. In the running application, select the first record.

  2. Move the sliders and change the checkbox selections.

  3. Click Save to save the changes into the database.

 

 

  1. In the Services window, use the View Data command again.

 

 

The values in the database should reflect changes that you have made.

 

Setting up a Custom Component

 

For an even more graphic demonstration of beans binding in action, let's add a custom component that will paint a preview of the selected car. We will bind properties of this component to corresponding table elements. Then when you run the application again, the car preview will be modified as you change the selected row and change the values of the various fields.

 

To make the CarPreview component available for the CarsApp project

 

  1. If you have not already done so, download the CarPreview.zip file.

  2. Using a standard zip tool, extract the archives of the zip file.

  3. Choose File > Open Project and navigate into the extracted contents of the zip file and select the CarPreview project.

  4. Click Open Project.

The project opens in the IDE.

 

 

  1. Right-click the CarPreview node and choose Build.

This compiles the files in the project so that you can use the CarPreview class as a bean that can be dragged and dropped directly on to the form.

 

This component was written as a JavaBeans component, so you could add it to the Palette, which would be convenient for adding the component to multiple applications. But for now we will simply drag the component directly into your application directly from the Projects window.

To add the CarPreview component to the application

 

  1. In the Projects window, expand the Car Preview > Source Packages > carpreview > nodes.

  2. Drag the CarPreview.java class to the form. To insert it properly just below the menus, place it over the table left aligned with the other controls and snapped to the bottom of the menu bar, as shown in the Figure below.

 

 

 

  1. Resize the preview component horizontally over the entire form.

 

 

  1. In the same way that you bound the sliders and checkboxes to elements in the masterTable component, bind all the binding properties of the CarPreview component to the corresponding selectedElement attributes of the masterTable. Use the Bind popup menu or the Binding tab in the property sheet. Step for color is shown below, repeat for make, modernness, spoiler, sunRoof, tiresize and tireType.

 

 

 

When the binding properties of the CarPreview component has been bound to the corresponding selectedElement attributes of the masterTable, the attribute is in bold.

 

 

  1. Run the CarApp application again.

In the running application, you can see the CarPreview component change as you select different rows in the table, alter values in the table, move the sliders, and select and deselect the checkboxes.

The following Figure shows the final running application.

 

 

 

 

 

 

 

 


 

< NetBeans & Java Desktop GUI 2 | Java & Friends | Recap: NetBeans & MySQL Database >