Kenji Tachibana's Weblog

« 前の日(Dec月 13日, 2008年) | 日付別メイン | 次の日(Dec月 15日, 2008年) »

http://blogs.sun.com/kenji/date/20081215 2008年 12月 15日 月曜日

How to connect Data Base from JavaFX UI with NetBeans.

This is English version of how to connect DataBase from JavaFX UI with Netbeans.

JavaFX is very compatible with Java class (JavaFX code will be compiled to Java Byte Code), and can use Java class from JavaFX script easily. So, you may would like to connect to DataBase from JavaFX UI, when you create cool UI by using JavaFX. Followings are very easy example of how to connect DataBase from JavaFX UI by using NetBeans. NetBeans can provide the many helps to create the connection to DataBase from Java, you can implement the database handling without any code. This example, shows, create a text field and button, and if you input the key in the textfield and click button, the application returns the related value, like input the ID and return the name of the user.



Step 1: Setup DB


In this example, use Derby (Java DB) for the databse. There are so many examples in NetBeans world to connect Derby from Java code by using NetBeans, so probably you have ever used this DB once. If you did not install Derby, please download the installer which contains derby and kick that installer again (download from netbeans.org).

- From "Services" tab in NetBeans, you can find "jdbc:derby://localhost:1527/..." entry in "DataBases". This is the bundled Derby schema.
- Right click "[app on APP]" and select "Connect".

- Right click "Java DB (Network)" in "Services" -> "Drivers" and Select "Connect Using"
- "New Database Connection" dialog is displayed. Input following values in that dialog, and click "OK" button.
o Host: localhost
o Port: your database port (typically 1527)
o Database: sample
o User name: app
o Password: app
- For schema selection, please chose APP and click OK

Now you complete the Database setting.



Step 2: Java setting - Generate Entity class


This step is to setup java class to access Database, which will perform like to connect to sample DB and get the corresponding value (from ID to Name). But, you don't need edit source code at all, because NetBeans generate all the code.

- Create some Java Application Project, by selecting "File" -> "New Project", chose "Java Application". Default is fine for all settings.
- The created project contains java package. Right click it and select "New" -> "Entity class from Database"
- Select the target database (in this example, use [App on APP]) in Database Connection, and select and add "CUSTOMER" from "Available Tables".

- Click "Next"
- You may see the warning like "The project does not have a persistence unit. You need a persistence unit to persist entity classes.". So, click "Create Persistence Unit" button
- Select "TopLink" from Persistence Library in "Create Persistence Unit" dialog, and clieck "Create" button.
- Back to "Net Entity Classes from Database" dialog, and click "Complete" button.



Step 3: Java setting - Create JPA Controller class


In this step, create JAP Controller.

- Right click the package in project and select "New" -> "Other".
- Select "JPA Controller class from Entity class" from "Persistence", and click "Next".
- Select all entity class from "Available Entity Classes" and add them to "Selected Entity Classes". Then, click "Next" button.

- Click "Finish" button



Step 4: Add Java DB Drivers Library


- Right Click "Libraries" in the project, and select "Add Library".
- Select "Java DB Driver" and click "Add Library" button



Step 5: Confirm the setting for Java.


Before creating JavaFX UI side, let's try to access the DB by using created java class. You may have Main.java class in the project, and use it to check the access to database.


public static void main(String[] args) {
// TODO code application logic here
CustomerJpaController test = new CustomerJpaController();
Customer idOne = test.findCustomer(1);
System.out.println(idOne.getName());

}


Above is to get "Name" field value from Customer DB, which ID is "1". If you can have output "JumboCom", the java setting is succeeded!



Step 6: Create outline with JavaFX UI


Now you can create JavaFX side. Please create New "JavaFX" project in NetBeans.

- "File" -> "New Project" -> JavaFX -> JavaFX Script Application

Followings are considering JavaFX application, to access database.

Use HBox to land textfield and button horizontally, and create a group with this textfield and button. Then, use VBox to land the group and Text vertically. The code in Stage will be as follows:


scene: Scene {
content: [
Group {
content: VBox {
content: [
Group {
content: HBox {
content: [
SwingTextField {
columns: 10
text: "textfield"
editable: true
},
SwingButton {
text: "OK"
}
]
}
},
Text {
font: Font {
size: 18
}
x: 10,
y: 50
content: "ResultText"
}
]
}
}
]
}

It's long code, but still empty.

Then, to include Java class, created before, you need to include following libraries:

o JRE libraries
o Toplink libraries
o Java DB drivers libraries.

For Toplink and Java DB drivers, you can add them by the same way as step 4. But, JRE is not defined as default libraries set (Because JDK platform in NetBeans contains it by default. So, NetBeans did not provide JRE as libraries set). So, you need to add jar files in JRE.

- Right click "Libraries" in your JavaFX project and select "Add JAR/Folders".
- Select all jars in JRE lib (for example, C:\Program Files\Java\jdk1.6.0_11\jre\lib), and click "Open" button.

Then, you also need to include the jar file, you created in your java project.

- Right click "Libraries" in your JavaFX project and select "Add Project".
- Select the java project created in step 2, and click "Add project Jar file".



Step 7: Create JavaFX UI detail


The last step is to create the function to access to database in JavaFX script. At first, create "tmpid" to bind textfield input.

var tmpid = "1";
:
:
SwingTextField {
columns: 10
text: bind tmpid with inverse
editable: true
},

Then, create CustomerJpaController instance to access to database. JavaFX can create a instance from Java class by using "new".

var DB = new CustomerJpaController();

CusotmerJpaController is a class defined in your java class, so you may need to resolve the import. Please right click editor, and select "Fix import" to resolve the reference issue (This is the one of the most powerful function in NetBeans. It's worth to learn how to use it). Then, create the function when the button is clicked. It will access to database by using input ID in the textfield, and get the value of Name field from the database. CustomerId is "int" value, which is converted from Sting "tmpid" by using Integer.parseInt method in java. Then, use JPA controller (DB) to get the "Name" field value.

SwingButton {
text: "OK"
onMouseClicked: function( e: MouseEvent ):Void {
CustomerId = Integer.parseInt(tmpid);
CustomerName = DB.findCustomer(CustomerId).getName();
}
}

Please use the same way to fix reference issue. But, only Integer class is the same name as JavaFX primitive type. So, please use following way to include Integer class in Java.

import java.lang.*;

The last thing is, create function to display the result in Text. This is simple to bind to "Name" string, which is get after clicking OK button.

Text {
font: Font {
size: 18
}
x: 10,
y: 50
content: bind Name
}

That's all!

# But, this code dose not have any exception handling, so if you input the invalid ID, it throws Exception. JavaFX can handle exceptions almost the same way as Java, like try - catch sentence.

The whole source file for JavaFX is here .

待っていたインド料理

私と嫁はインド料理が大好きで、家でも、よくわからないスパイスを買ってきては、カレーを作ってみているのですが、近くに本格インド料理屋ができたのはうれしいです。



やるき ZOU


横浜市青葉区藤が丘1-16-10 アーバンプラザ1F


オーダー: やるき ZOU C セット


コメント:
藤が丘周辺では一番いった回数が多いと思います。カレー好きなのもありますが、ほかのお店に比べたら安いので。セットで大体 2000 円弱ぐらいでしょうか。ボリュームもたっぷりでおなかいっぱいになります。ただ、ブログにも何度か書きましたが、インド料理はどうしても、インド本国のものと比較してしまうのです。やっぱり、インド料理はインドで食べるのが一番おいしいですね。値段も、1/5 ぐらいですし。なので、それを差っぴけば、かなり味は Good だと思います。マトンカレーが私のお勧めです。後は、大きく丸く膨らんだパン (名前は忘れてしまいました... ドサをもっと大きく膨らましたような感触です。)


評価: ★★★★☆


Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.