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).
This tutorial was written to work with the NetBeans IDE 6.0 Preview (Milestone 9) build.
The tutorial will not work with
earlier milestone builds. Also, there might be some changes in later builds that
affect the accuracy of this tutorial.
This tutorial is largely based on this video demo, which was based on an earlier
development build. Some of the user interface has changed since that demo
was made, so you might notice some differences between this tutorial and the demo.
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:
To manually register Java DB in the IDE:
- Choose Tools > Java DB Database > Settings.
- In the Java DB Installation field, enter the path to the database server.
- In the Database Location property, enter the folder where you want the databases to be stored.
- Click Close.
Once Java DB is registered with the IDE, the Java DB Database menu item appears
under Tools in the main menu. This menu item enables you to easily start and stop
the database server, as well as create a new database.
To start the database server:
- Choose Tools > Java DB Database > Start Java DB 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 the following:
Apache Derby Network Server - 10.2.2.0 - (485682) started and ready
to accept connections on port 1527 at 09-05 10:26:25.424 GMT
To create the database:
- Choose Tools > Java DB Database > Create Java DB Database. The
Create Java DB Database dialog opens.
- For the Database Name text field, type car_database. Also set the User Name and
Password to nbuser.
- Click OK.
So far, we have successfully started the 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:
- Switch to the Services window (Ctrl+5) and expand the Databases node to see
your new database.
- 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 (), which signifies that the connection was successful.
- Right-click the Tables subnode of the connection node and choose Execute Command.
- Copy the contents of the
car.sql file
and paste them into the SQL Command 1 tab of the Source Editor.
This is the SQL script which will populate the database with data about cars.
- Click the Run SQL button ()in
the toolbar of the Source Editor to run the script.
- Choose Project > New Project.
- In the first panel of the wizard, expand the General 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.
- In the Name and Location page of the wizard, do the following things:
- In the Project Name field, type CarsApp. The value of this field sets the display name for the project in the Projects window.
- Optionally, edit the Project Location field to change the location of your project metadata.
- In the Choose Application shell field, select Database Application.
- Click Next.
- 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: jdbc:derby://localhost:1527/cars[nbuser on NBUSER]
- Fill in the password (nbuser) for the database and select the
Remember Password During This Session checkbox.
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.
- Select the bottom five column names (beginning with
SUN_ROOF and ending with MODERNNESS) and click the < button. Click Next.
- In the Detail Options panel, click Finish.
The wizard then generates the a basic user interface with a table and a
database connection.
At this point, you have a basic running application with a
graphical user interface (GUI) that has the following features:
- Ability to view and modify values in five columns of the CAR database.
- Basic menu items.
- Persistence of its window state between sessions. When you
close the application, the window position and size are remembered. So
when you reopen the application, the window opens in the same position as
it was when you closed it.
- An About dialog box, which you can easily customize.
- .properties files containing the labels in the user interface. Using
.properties files is a good way to keep the logic of your code separate from the
text that appears in the user interface of your application. Such separation is useful
for making it easier to localize your program, among other reasons.
To see some of the features that are already built into the application, follow these steps:
- Right-click the project's node and choose Run Project.
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.
- Select the first record in the table (for the Acura).
- Select the Price text field and replace the existing value with 46999. Then press Enter.
The value in the table should be updated.
Similarly, you can update any other values in the table.
- Click New to create a new record. Then fill in values for each of the fields (Make, Model, Price, Body Style, Color). For example, you can fill in
Traband, Classic, 1000, wagon, and blue. Click Save to
save the entry in the database.
- Click the Database Application Example title bar and drag the application to a different place on your screen.
- Click the left border of the Database Application Example window and drag to the left to increase the size of the window.
- In the Database Application Example menu bar, choose File Exit.
- 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.
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:
- 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 enable you to interact with databases through Java code.
Entity classes use Java annotations to map class fields to database columns. .
- 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.
- 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 will probably be included in a future Java SE release.
- The entityManager, query, and list
objects, which are defined in the CarsAppFrame class and
which are listed in the Inspector window under the Other Components node.
- The entity manager object is used to retrieve and commit data
within the defined persistence unit scope.
- The query object defines how the particular data collection is retrieved from
the entity manager. (You can change the way that the query object works by selecting the
query object in the Inspectory window and changing the query property in the property sheet.
The query property uses JPA query language.
- The list object is an observable collection that holds the data from the query. An
observable collection is a special kind of collection on which you can place a listener to
find out when changes to the collection have been made.
Using the Inspector window and the property sheet, you can follow these steps to see how
the JTable is bound to data:
- In the Inspector window, select the
[JFrame] > innerPane [JPanel] > masterScrollPane [JScrollPane] > masterTable (JTable) node.
Then click the Binding tab in the Properties window.
- Look at the elements property to confirm that it is bound to a list.
- 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.
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:
- Add the first slider by clicking the JSlider 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, the easiest way to recover might be to close
the form without saving the changes. Then re-open the form and try again.
- If necessary, stretch the slider to the left to align it with the left side of the text field components.
- Stretch the slider to the
right to span the whole form width.
- Add a label to the left of the slider and set its text to Tire Size.
(Click the label to make it editable.)
- Add another slider below the first slider, and adjust its width and alignment where necessary.
- Add another label below the Tire Size label and set its text to Modernness.
- Add two checkboxes below the sliders. Set their text to Spoiler and Sun Roof.
The form should look like the screenshot shown below.
"
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.
Since no record is selected when the application starts, we also need to
set a default value for the source of the binding expression. For the sliders,
we will do this through the Advanced tab of the Binding dialog box. For the
checkboxes, we will add the code manually in the Customize Code dialog box.
To bind the sliders to their corresponding table elements:
- In the form, right-click the first slider and choose Bind > value.
- In the Binding Source drop-down list of the Binding dialog box, select masterTable.
- In the Binding Expression drop-down list, select selectedElement > tiresize.
- Click the Advanced tab.
- Select the Unreadable Source Value checkbox.
- Click the ellipsis (...)button that is next to the Unreadable Source Value checkbox.
- In the Incomplete Path Value dialog box, select Custom Code from the
drop-down list. Then type the integer 0.
- Click OK to close the Incomplete Path Value dialog box.
Then click OK to close the Bind dialog box.
- In the form, right-click the second slider and choose Bind > value.
- In the Binding Source drop-down list of the Binding dialog box, select masterTable.
- In the Binding Expression drop-down list, select selectedElement > modernness.
- Repeat steps 4 through 8 to set the Incomplete Path Value.
"
To bind the checkboxes to their corresponding table elements:
- In the form, right-click the first checkbox and choose Bind > selected.
- In the Binding Source drop-down list of the Binding dialog box, select masterTable.
- In the Binding Expression drop-down list, select selectedElement > spoiler.
- Click OK.
- Right-click the checkbox and choose Customize Code.
- In white line under the bindingGroup.addBinding(binding) line, type:
binding.setSourceUnreadableValue(false);
- Click OK to close the Customize Code dialog box.
- In the form, right-click the second checkbox and choose Bind > selected.
- In the Binding Source drop-down list of the Binding dialog box, select masterTable.
- In the Binding Expression drop-down list, select selectedRow > sunRoof.
- Click OK.
- Repeat steps 5 through 7 for the second checkbox.
You should now be able to change database entries using the slider and
checkboxes.
To verify that the sliders and checkboxes work:
- Open the Services window.
- Make sure the IDE has a connection to the database by right-clicking
Databases > jdbc:derby;//localhost:1527/car_database and choosing Connect.
- Right-click the Databases > jdbc:derby;//localhost:1527/car_database > Tables > node
and choose View Data.
- Look at the SUN_ROOF, SPOILER, TIRE_SIZE, and MODERNNESS values
for the first record.
- Choose Run > Run Main Project to execute the application.
The running application should look similar to the screenshot shown below.
- In the running application, select the first record.
- Move the sliders and change the checkbox selections.
- Click Save to save the changes into the database.
- In the Services window, use the View Data command again.
The values in the database should reflect changes that you have made.
The running application should look similar to the screenshot shown below. You should
be able to use the sliders and checkboxes in the running application to
change values in the selected record.
"
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:
- If you have not already done so, download the CarPreview.zip file.
- Using a standard zip tool, extract the archives of the zip file.
- Choose Project > Open Project and navigate into the extracted contents of the zip file and select the CarPreview project.
- Click Open Project.
The project opens in the IDE.
- 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:
- In the Projects window, expand the
Car Preview > Source Packages > carpreview > nodes.
- 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 toolbar, as
shown in the image below.
- Resize the preview component horizontally over the entire form.
- With the preview component still selected in the design area,
- 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.
- 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 image below shows the final running application.
Next Steps
This tutorial has provided an introduction to support for the Swing Application
Framework and Beans Binding in the IDE. For a more general introduction to using the
IDE's GUI Builder, see GUI Building in NetBeans IDE 5.5.
For more information on Beans Binding, see the
Beans Binding project page on java. For more
information on the Swing Application Framework, see the
Swing Application Framework project page on java.