创建一个 Java 应用数据库的桌面应用程序

来源:互联网 发布:配电柜电路图软件 编辑:程序博客网 时间:2024/05/20 19:32

创建一个 Java 应用数据库的桌面应用程序

NetBeans 中文社区的 solaris_navi 翻译

Content on this page applies to NetBeans IDE 6.0本教程将展示如何创建一个 Java 的桌面应用程序,用来访问以及更新数据库。本教程利用 NetBeans IDE 6.0 支持的以下技术:

    * Java 持久化 API (JPA),帮助你使用Java 代码来与数据库接合

    * Beans 绑定技术 (JSR 295) ,为不同的JavaBeans 控件提供一种方式来相互同步属性值。举一个例子, 你可以使用 Beans 绑定技术来保持 JTable 可视化控件中各单元的值与实体类中各域的值同步。 (在这里,实体类表示数据表)

    * Swing 应用程序框架 (JSR 296) ,提供了一些十分有用的构件,用来快速建立桌面应用程序。

我们将建立一个数据库 CRUD (增、删、改、查)的应用程序,使用一个自定义的控件用来形象化数据(汽车设计预览)。

本教程大多基于开发过程中的截图。用户界面中的一些部分在演示程序制作中可能有改变,所以您可能会注意到教程与演示程序中的一些不同。您可以现在浏览演示程序(预计约9分钟) 或者 下载演示程序( zip 格式).

预计持续时间:45 分钟

教程所需的软件以及文件

学习这个教程,你需要在你的计算机上安装以下软件:

    * NetBeans IDE 6.0 (下载).

    * Java 标准开发工具包 (JDK) 版本 5.0 或者 6.0 (下载)

    * Java DB 数据库服务器 (Java DB 已包含在 JDK 6)

    * 数据库的 SQL 描述,参阅 http://usersguide.netbeans.org/files/documents/40/1423/car.sql.

* CarPreview project 的工程文件包,参阅

http://usersguide.netbeans.org/files/documents/40/1433/CarPreview.zip

建立数据库

IDE 中开始创建一个 CRUD(增、删、改、查) 桌面应用程序之前, 您应该已经把您的 IDE 链接上应用程序使用的数据库了。 完成这项链接高级设置可以允许您使用 IDE 的高级特性, 帮助您自动的把数据库与您的应用程序绑定起来。

在本教程中,我们提供了使用 Java DB 数据库的教程, 因为在 IDE 中提供了很方便的界面来启动以及停止 Java DB 数据库。 不过,如果不麻烦的话,您也可以选择其他的数据库。

首先检查您是否在 IDE 中注册了Java DB 一般来说,Java DB 是自动在 IDE 中注册的, 比如说当您在 IDE 中注册了 Sun Java System Application Server 或者您在 JDK 6 上运行程序的时候。

确定 Java DB 已经在 IDE 中注册:

    * 打开“工具”菜单,点击 Java DB Database 的子菜单。

      如果“设置”菜单是唯一一个没有标记不可用的, 您需要在 IDE 中手动启动 Java DB 的注册。

IDE 中手动注册 Java DB

   1. 选择 工具 > Java DB Database > 设置.

   2. Java DB 安装路径中输入数据库服务器的安装路径

   3. 在数据库位置属性中,选择一个文件夹来存储数据库文件。

   4. 单击确定。

服务器的启动以及数据库的创建

一旦 Java DB IDE 中注册成功,您可以很简单的启动或者停止数据库服务器, 当然,创建一个新的数据库也是如此简单。

启动数据库服务器:

    * 选择 工具 > Java DB Database > 启动服务器.

      如果您还没有在“设置”中为数据库设置数据库文件存储位置, “设置数据库位置”的对话框将会出现,为数据库文件输入一个存储的位置, 当然,您也可以根据您的需要新建一个文件夹。

      一旦服务器启动,Java DB 数据库进程的标签会显示在“输出”窗口, 显示如下的一段消息:

      Apache Derby Network Server - 10.2.2.0 - (485682) started and ready

                  to accept connections on port 1527 at 2007-09-05 10:26:25.424 GMT

创建数据库:

   1. 选择 工具 > Java DB Database > 创建数据库. 出现创建 Java DB 数据库的对话框。

   2. 在数据库名称中输入 car_database,并且设置数据库的用户名和密码为 nbuser

   3. 单击确定。

链接数据库

到此,我们成功的启动了数据库服务器并且创建了一个数据库。 但是在 IDE 中开始工作前,我们仍然需要连接这个新的数据库。 链接 car_database 数据库:

   1. 转到“服务”窗口( Ctrl + 5 ),展开 Databases 节点查看您的新数据库。

   2. 右键单击数据库连接节点, (jdbc:derby://localhost:1527/car_database[nbuser on NBUSER]),选择“链接”。 Connect.

      链接节点的图标现在应该完全变成了 (connection node icon),表示链接成功。

      car_database under Databases node in Services window

   3. 展开联机金额节点,右键单击其数据表的子节点,选择“运行命令”。

   4. 拷贝 car.sql 文件中的内容, 并将其粘贴在 Source Editor 的标签“ SQL Command 1 ”中。

      粘贴的这些内容是 SQL 的描述语句,他将汽车的一些数据植入到数据库中。

   5. Source Editor 的工具栏上点击“运行 SQL ”按钮 (Run SQL button) 运行。

创建应用程序

   1. 选择 项目 > 新项目。

   2. 在向导的第一页,展开 Java 类并选择 Java 桌面应用程序模板。 单击下一步。

      Java 桌面应用程序模板提供了许多基本的可视化应用模块,包括菜单以及按钮。

   3. 在向导的 Name and Location 页面中,做以下事情:

         1. 在项目名称中输入 CarsApp。这个值设置了在项目窗口中显示的该项目的名称。

         2. 另外,也可以根据您的需要更改项目路径中更改项目的元数据位置。

         3. 在选择应用程序类型处选择数据库应用程序。

         4. 单击下一步。

   4. 在向导的 Master Table 页面中,为数据库 CAR 选择数据库连接。 数据库列表应同以下所示: jdbc:derby://localhost:1527/car_database[nbuser on NBUSER]

   5. 为数据库填写密码 (nbuser) 并选择 Remember Password During This Session 选项。

      在与数据库建立连接后,数据表应该显示为 CAR 其包含的列应包括 10 CAR 数据库的内容的名称。 现在,我们的应用程序中只用其中的5列。

   6. 选择倒数5列的名称 ( SUN_ROOF 起到 MODERNNESS ) 并点击 < 按钮 移动他们到左侧的列表中。 单击下一步。

   7. Detail Options 页中, 单击完成。

      向导其后会生成基本的用户界面,包含一个表格以及一个数据库连接。 IDE 生成项目以及代码的过程可能会耗费几秒钟或更长一些的时间。

运行生成的程序

这个时候,您就有了一个最基本的用户图形界面( GUI )应用程序, 有如下功能:

    * 能够查看以及修改数据库 CAR 的五个添加列的值。

    * 基本的菜单项。

    * 在会话过程中保存当前窗口的状态信息。 当您关闭应用程序的时候,窗口的位置以及大小会被记录。 这样,当您再次运行这个应用程序的时候,窗口会在上次关闭的位置被打开。

    * 一个“关于”对话框,您可以很简单的装扮它。

    * .properties 文件含有用户界面中的标签( Labels )内容。 使用 .properties 文件是一个很好的方式,您可以将您的逻辑代码和要在用户界面中显示的 文本信息分割开来。这种分割最起码可以使得您的程序可以更容易的被本地化。

按照以下步骤查看已经在应用程序中建立好的一些特性:

   1. 右键单击“项目”节点,选择“运行”。

      稍等片刻,应用程序启动,出现一个叫做“ Database Application Example ”的窗口。 这个窗口包含一个表格以及一些控件,您可以通过这些控件来编辑 CAR 数据库。

   2. 选择表格中的第一个记录( Acura )。

   3. 选择价格( Price )这个字段的值,将其存在的值改为 46999 。然后按回车。

      这时,这个值在表格中显示被更改了。(不过,当您单击保存之后这个值才会写入数据库中。)

      同样,您可以用这种方法更新表格中其他的值。

   4. 单击新建按钮创建一个新的记录。 之后为每一个字段( Make, Model, Price, Body Style, Color )填写相应的值。 比如您可以填写: TrabantClassic1000wagon,以及 blue 单击保存来保存这些数据到数据库中。

   5. 点击并按住 Database Application Example 的标题栏,拖动到您的屏幕的其他位置上。

   6. 点击并按住 Database Application Example 窗口的左侧边框 向左边拖动,改变这个窗口的大小。

   7. Database Application Example 的菜单栏,选择 File > Exit

   8. IDE 中,右键单击“项目”节点,选择“运行项目”。

      Database Application Example 窗口将会按照以您关闭应用程序时候所改变的窗体位置以及大小打开。

回顾应用程序的生成部分

主表(一个 JTable 控件)和数据库之间的连接被如下 IDE 生成的一个组合机制所解决:

    * 实体类 Car.java 用于读写数据库 CAR 中的数据。 实体类是一种特殊的类,使得您可以通过 Java 代码来让您的程序与数据库相结合。 实体类使用 Java 的注释将类中字段映射到数据库的列中。.

    * META-INF/persistence.xml 文件定义了数据库与实体类之间的关联。 这个文件也是众所周知的一个持久化单元。

    * 使用 beans 绑定技术将实体类中的属性与 JTable 控件中的属性相关联。 Beans 绑定技术是一个基于 JSR 295 的一项新技术,它或许会被包含在 Java SE 的后续版本中。

    * CarsAppFrame 中定义了 entityManager query 以及 list 对象并列在 Inspectory 窗口中。

          o 实体管理器对象用来在已定义的持久化单元的域中检索以及提交数据。

          o 查询对象定义指定的数据集如何向 entityManager 对象检索数据。 (您可以通过选择在 Inspectory 窗口中的查询对象,改变 query 属性表里的属性值改变查询方式。 query 属性使用 JPA 查询语言。

          o 列表对象是一种可观察集,其持有来自查询的数据。 可观察集是集合的特殊种类,您可在其上设置一个监听器, 来查看何时对集合做出的更改。

使用 Inspector 窗口和属性表,您可以按照如下步骤看到 JTable 如何绑定数据:

   1. Inspector 窗口中,依次选择 mainPanel[JPanel] > masterScrollPane [ScrollPane] > masterTable [JTable] 节点。 然后在“属性”窗口中单击 Binding 标签。

   2. 查看元素属性,确认其与列表已绑定。

   3. 单击省略号 [...] 按钮,打开 Bind masterTable.elements 定制器, 您可以更进一步定制表格和数据库的绑定。 举个例子,您可以看到使用定制器您能够绑定指定的表中的列。

除了属性表中的 Binding 种类外,您还可以使用上下文菜单中的 Bind 菜单。

添加更多的控制

针对一些我们起初排除的属性,我们现在向表单添加控件。替代使用表格, 我们将添加 Jslider 组件(用于 tire size modernness JCheckbox 组件(用于 sun roof spoiler )来实现操作的相应功能。.

根据以下步骤添加额外的控件:

   1. 添加第一个滚动条,在 Palette 窗口中单击 Slider 按钮, 然后单击 New 按钮上方的窗体。在单击窗体插入滚动条之前, 请确定没有出现水平槽引导线。 这些线条表示滚动条将被插入在与文本域或按钮的同一行。 参照下图了解应将滚动条放在表单的位置。 Image showing the proper placement of the JSlider before dropping it into the form

      提示: 如果你将控件放置在了您不想要的位置上,因此造成了一些布局上不期望的改变。 您可以使用“撤销”命令撤销这些修改。选择 Edit > Undo 或者按 Ctrl-Z

   2. 如果需要,将滚动条向左边伸展并文本框控件的左边对齐。

   3. 将滚动条向右边伸展横跨整个窗体宽度。

   4. 在滚动条左边添加一个标签,并设置其显示的文本为 Tire Size (点击标签令其可编辑。)

   5. 在第一个滚动条下面添加另一个滚动条, 按照需要调整好它的宽度以及对其方式。

   6. Tire Size 标签下面添加另外一个标签,并设置其显示的文本为 Modernness

   7. 在滚动条的下面添加两个复选框,将它们的名称分别设置为 Spoiler 以及 Sun Roof. (用点击复选框一次,稍等片刻,再次点击复选框 这种方式使得显示文本可被编辑。 您也可以用右键单击复选框后选择编辑文本。)

窗体应该如如下截图一样。

A screenshot of the design area with all controls added"

将控件与表格中的值进行绑定

我们现在将使用 beans 绑定技术特性,将表格单元中显示的值和我们已经添加的控件的状态绑定。 这将使您可以通过滚动条和复选框改变表格单元中的值。

将滚动条绑定至相对应的表元素:

   1. 在窗体中,右键单击滚动条 Tire Size 后选择 Bind > value

   2. Binding 对话框的 Binding Source 的下拉列表中,选择 masterTable

   3. Binding Expression 的下拉列表中,选择 selectedElement > tiresize node

   4. A screenshot of the Bind dialog box showing the modernness field being bound to the second slider" 在窗体中,右键单击滚动条 Modernness 后选择 Bind > value

   5. Binding 对话框的 Binding Source 的下拉列表中,选择 masterTable

   6. Binding Expression 的下拉列表中,选择 selectedElement > modernness

将复选框绑定至相对应的表元素:

   1. 在窗体中,右键点击复选框 Spoiler 后选择 Bind > selected

   2. Binding 对话框的 Binding Source 的下拉列表中,选择 masterTable

   3. Binding Expression 的下拉列表中,选择 selectedElement > spoiler

   4. 单击 OK 退出 Bind 对话框。

   5. 在窗体中,右键点击复选框 Sun Roof 后选择 Bind > selected

   6. Binding 对话框的 Binding Source 的下拉列表中,选择 masterTable

   7. Binding Expression 的下拉列表中,选择 selectedRow > sunRoof

   8. 单击 OK

您现在可以使用滚动条以及复选框改变数据库的输入项了。

验证滚动条和复选框是否工作:

   1. 打开 Services 窗口。

   2. 确定 IDE 已经与数据库相连接,链接请右键单击 Databases > jdbc:derby;//localhost:1527/car_database 然后选择 Connect

   3. 右键单击 Databases > jdbc:derby;//localhost:1527/car_database > Tables > node 并选择 View Data

   4. 查看 SUN_ROOF, SPOILER, TIRE_SIZE 以及 MODERNNESS 的第一个记录集的值。

   5. 选择 Run > Run Main Project 运行程序。

      运行中的应用程序应看起来与下面显示的截图相似。

      A screenshot of the Bind dialog box showing the modernness field being bound to the second slider"

   6. 在运行中的应用程序里,选择第一个记录集。

   7. 移动滚动条并更改复选框的选项。

   8. 单击保存按钮将更改内容写入数据库。

   9. Services 窗口中,再次使用 View Data 命令。

      数据库中的值应该被更改为您所更改的值。

建立一个自定义控件

为了更加图形化的演示 Beans 绑定技术的运行让我们添加一个自定义控件, 画出选择出的车的预览图。我们将绑定此控件的属性以及所对应的表格元素。 然后当您再次运行程序,车辆预览将按照您选择的行以及各个字段的值的变化而改变。

CarPreview 控件可在 CarsApp 项目中可被应用:

   1. 如果您还没有完成这些,请下载文件 CarPreview.zip

   2. 使用标准 zip 工具,解压此 zip 文件的档案内容。

   3. 选择 File > Open Project ,定位解压后的 zip 文件的档案内容, 然后选择 CarPreview 项目。

   4. 点击“打开项目”

      项目在 IDE 中被打开。

   5. 右键单击 CarPreview 节点,然后选择 Build

      编译此项目中的文件,这样您可以将 CarPreview 类作为一个 bean 来使用, 可以将其直接拖拽到窗体中。

这个组件被写为一个 JavaBeans 组件,这样您可以将其添加到 Palette 中,这样您可以很方便的将 这个组件添加到多个应用程序中。但是现在我们将简单的将此组件直接从“项目”窗口拖动到您的程序中。

CarPreview 控件添加到应用程序:

   1. 在“项目”窗口中,依次展开 Car Preview > Source Packages > carpreview > nodes.

   2. 拖动 CarPreview.java 类到窗体中。将其插入到菜单的下方,将其放在窗体上,左对齐于其他的控件, 并与工具栏的底部对齐,如下图所示。 Screenshot showing how to add the car preview component to the form

   3. 在窗体上水平方向调整预览组件。

   4. 采用与滚动条和复选框绑定 masterTable 组件中的元素相同的方法, 绑定所有 CarPreview 组件中的属性到 masterTable 中相应的 selectedElement 属性。 使用 Bind 弹出菜单或者属性表中的 Binding 标签。

   5. 再次运行 CarApp 应用程序。

n

      在运行中的应用程序中,您可以看到 CarPreview 控件根据您选择的表格中不同的行, 改变表格中的值,移动滚动条以及选择和取消选择复选框而改变。

下图为应用程序的最终运行结果。

Screenshot showing the final running application with the Toyota record showing

进阶

本教程为在IDE 中使用 Swing 应用程序框架以及 Beans 绑定技术提供了初步教程。

了解更多关于 GUI 应用程序的设计,参阅 Designing a Swing GUI.

了解更多关于在 IDE 中使用 Beans 绑定技术, 参阅 Binding Beans and Data in a Desktop Application.

Send Us Your Feedback

参阅

    * Beans Binding project page on java.net

    * Swing Application Framework project page on java.net

    * GUI Editor FAQ

    * Patrick Keegan's web log on Swing development in NetBeans IDE

    * Java EE Tutorial: Introduction to the Java Persistence API

 

原文

Building a Java Desktop Database Application

Content on this page applies to NetBeans IDE 6.0 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:

    * The Java Persistence API (JPA), which helps you use Java code to interact with databases.

    * Beans Binding (JSR-295), which provides a way for different JavaBeans components to have property values that are synchronized with each other. For example, you can use beans binding to keep the values of cells in a JTable visual component in synch with the values of fields in an entity class. (In turn, the entity class represents the database table.)

    * The Swing Application Framework (JSR-296), which provides some useful building blocks for quickly creating desktop applications.

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 is largely based on a screencast that was based on a 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. You can view the demo (about 9 minutes) now or download a zip of the demo.

Expected duration: 45 minutes

Software and Files Needed for the Tutorial

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

    * NetBeans IDE 6.0 (download).

    * Java Standard Development Kit (JDK) version 5.0 or 6.0 (download)

    * Java DB database server (Java DB is included with JDK 6)

    * The SQL script that is located at http://usersguide.netbeans.org/files/documents/40/1423/car.sql.

    * The CarPreview project, which is located at

http://usersguide.netbeans.org/files/documents/40/1433/CarPreview.zip

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:

    * Open the Tools menu and open the Java DB Database sub-menu item.

      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:

    * Choose Tools > Java DB Database > Start 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 2007-09-05 10:26:25.424 GMT

To create the database:

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

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

   3. Click OK.

Connecting to the Database

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:

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

   2. 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.

      car_database under Databases node in Services window

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

   4. 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.

   5. Click the Run SQL button (Run SQL button)in the toolbar of the Source Editor to run the script.

Creating the Application

   1. Choose File > New Project.

   2. 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.

   3. 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. Select the Set As Main Project checkbox.

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

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

         5. Click Next.

   4. 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/car_database[nbuser on NBUSER]

   5. 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.

   6. 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.

   7. In the Detail Options panel, click Finish.

      The wizard then generates the 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:

    * 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:

   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.

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

   3. 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.

   4. 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 Trabant, Classic, 1000, wagon, and blue. Click Save to save the entry in the database.

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

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

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

   8. 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:

    * 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.

          o The entity manager object is used to retrieve and commit data within the defined persistence unit scope.

          o 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.

          o 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:

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

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

   3. 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:

   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. Image showing the proper placement of the JSlider before dropping it 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.

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

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

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

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

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

   7. 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.)

 

The form should look like the screenshot shown below.

A screenshot of the design area with all controls added"

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. In the form, right-click the Tire Size slider and choose Bind > value.

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

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

   4. A screenshot of the Bind dialog box showing the modernness field being bound to the second slider" In the form, right-click the Modernness slider and choose Bind > value.

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

   6. 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.

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

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

   4. Click OK to exit the Bind dialog box.

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

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

   7. In the Binding Expression drop-down list, select selectedRow > sunRoof.

   8. 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.

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

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

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

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

      A screenshot of the Bind dialog box showing the modernness field being bound to the second slider"

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

   7. Move the sliders and change the checkbox selections.

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

   9. 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.

   5. 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 image below. Screenshot showing how to add the car preview component to the form

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

   4. 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.

   5. 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.

Screenshot showing the final running application with the Toyota record showing

Next Steps

This tutorial has provided an introduction to support for the Swing Application Framework and Beans Binding in the IDE.

For a more information on designing GUI applications, see Designing a Swing GUI.

For more information on using beans binding in the IDE, see Binding Beans and Data in a Desktop Application.

Send Us Your Feedback

See Also

    * Beans Binding project page on java.net

    * Swing Application Framework project page on java.net

    * GUI Editor FAQ

    * Patrick Keegan's web log on Swing development in NetBeans IDE

    * Java EE Tutorial: Introduction to the Java Persistence API

 

 

 
原创粉丝点击