Mar 09
Posted: under Citizenship.
Tags: canada, Canadian, Citizenship, new, TestMarch 9th, 2010
From March 15, 2010 on, the Canadian citizenship test is based on a new study guide: ‘Discover Canada”. Compared with the old study guide ‘A Look at Canada’, it is a more comprehensive document. If you have studied the old book but now you are required to take the new test, here is a list [...] [...more]
From March 15, 2010 on, the Canadian citizenship test is based on a new study guide: ‘Discover Canada”. Compared with the old study guide ‘A Look at Canada’, it is a more comprehensive document. If you have studied the old book but now you are required to take the new test, here is a list of the new content that you should pay attention to:
1. More details about the Canadian history. It has a section of more than 10 pages about the history of Canada and 4 pages about Modern Canada. It describes the Aboriginal peoples, British and French as the founding people of Canada. Canada’s role in two world wars is detailed. Many histroic people are introduced so you may have more names to remember before sitting for the test. It is interesting to see that the study guide admits the historic wrongdoings of the Canadian government, such as the “Head Tax”, wartime wrongs inflicted on Japanese and education of Aboriginal children.
2. There are wording changes about the Canadian government, though the concepts are mainly the same. In the old book, it states Canada’s government has a system of parliamentary government. It is now in the new book as “a federal state, a parliamentary democracy and a constitutional monarchy.”
3. The concept of Sovereign is emphasized in the new book. A bill must be finally approved by ‘royal assent’.
4. The section about federal election is mostly unchanged except for the election cycle. In 2007, new laws passed to force a general election at least every 4 years and has a fixed date. The new book reflects this lastest change in legislation.
5. Justice System is the new content not seen in the old book, so you must know about it.
6. Canada Regions are now in more details. The new book covers each province/territory separately. Therefore, you must know at least the region you are in.
7. Canadian symbols now include “Coat of Arm and Motto”, honours to Canadians, sports and holidays.
If you are preparing for the Canadian citizenship test after March 15, 2010, you can use a good online practice web site which provides practice questions of the New Canadian Citizenship Test.
Related Links:
US Citizenship Application for people to apply for their American citizenship and prepare for the US Citizenship Test.
Crystal jewelry, necklaces, crystal earrings, ring crystal bracelets
Jan 18
Posted: under JavaFX.
Tags: applet, java, JavaFX, performance, web startJanuary 18th, 2010
Unlike the u17, the u18 update is not released for security, instead, it introduces many improvements on performance.
Faster Jar File Creation If you application need to create a lot of jar files, you will see about 20 percent improvement.
Hotspot VM Enhancement This includes some hardware-aware features, garbage collection improvements, class loading optimization and compile time [...] [...more]
Unlike the u17, the u18 update is not released for security, instead, it introduces many improvements on performance.
Faster Jar File Creation If you application need to create a lot of jar files, you will see about 20 percent improvement.
Hotspot VM Enhancement This includes some hardware-aware features, garbage collection improvements, class loading optimization and compile time optimization on code generation. The improved G1 garbage collector is still not yet ready for production, unless you have business support contract with Sun.
Application Startup Time Improvements If you are using JavaFX, you will notice about 20 percent improvement when launching an FX application. Web start and applet application can now download jar files concurrently.
Other improvements include runtime UI application performance, zip file reading and deployment updates. For more info, please check out here.
Other links:
JavaFX Plug-in for Eclipse 3.5.x
javaFX used in Winter Olympics 2010
Review on Essential JavaFX
JavaFX How-tos
Australian Citizenship Test
Free British citizenship Test
US Citizenship Application
Java SE U18的性能提高
Dec 22
Posted: under JavaFX.
Tags: JavaFX, olympicsDecember 22nd, 2009
I am not sure if this is the first web site that uses JavaFX for production, the official web site of the Vancouver Winter Olympics 2010 is using JavaFX for displaying the medal history of the Winter Olympics Games. In this winter, Vancouver is probably hot for Olympics, so is JavaFX. ( Check it out [...] [...more]
I am not sure if this is the first web site that uses JavaFX for production, the official web site of the Vancouver Winter Olympics 2010 is using JavaFX for displaying the medal history of the Winter Olympics Games. In this winter, Vancouver is probably hot for Olympics, so is JavaFX. ( Check it out here: http://www.vancouver2010.com/olympic-medals/geo-view/ )
This is a very cool demo (oh, I should say real world application) of the JavaFX visualization technologies. Overall, it works well except for some animations were not so smooth. Though the same effects can be achieved by Flash, I would say this is a good start for JavaFX going into practical use. Hope to see more and more such applications in JavaFX.
Other Links:
Games in JavaFX
JavaFX Resources
British Citizenship Test: Life in the United Kingdom Test for settlement and Citizenship
UK Citizenship Test on iPhone
Dec 04
Posted: under JavaFX.
Tags: essential, JavaFX, reviewDecember 4th, 2009
It has been a year since the official release of JavaFX. JavaFX had gone through 3 major releases and now the current version is 1.2.1. There are a few books out there on JavaFX. Today I would introduce the book “Essential JavaFX” by Gail Anderson and Paul Anderson. The book is also available in Chinese [...] [...more]
| It has been a year since the official release of JavaFX. JavaFX had gone through 3 major releases and now the current version is 1.2.1. There are a few books out there on JavaFX. Today I would introduce the book “Essential JavaFX” by Gail Anderson and Paul Anderson. The book is also available in Chinese and it was translated by Sun Asian Globalization Center. You can read my review in Chinese.
|
|
|
Gail and Paul are the founders of Anderson Software Group, Inc. They are both experienced software professionals and instructors. They have coauthored a few textbooks. “Essential JavaFX” is their latest book for people to learn the JavaFX script language. The JavaFX team at Sun had provided technical guidance for the book. The content conformed the JavaFX 1.2 SDK. For this reason, the book can serve as an excellent textbook for students or beginners. Other JavaFX programmers may also find it helpful as a reference resource.
As stated in the preface, the book is primarily for developers with some previous experience in any programming language(not necessarily Java). Readers without any programming experienced are advised to first learn some language such as Java or C++. In my opinion, because the strong intrinsic relationship between JavaFX and Java, I would consider that Java programmers are the most likely to learn JavaFX and have the lowest barrier to master it. Other developers with OO (Object Oriented) programming experience may also find familiar concepts and syntax in JavaFX.
I have multiple years of experience in various programming languages such as VB, Java and C++. When I start to learn a new language, I usually go through a HelloWorld like example to quickly understand its style and characteristics. Then I will skim through its grammar or syntax. After I got some basic ideas, I will dive into the details of each language construct. I find this approach extremely effective. Since the chapters of the book are organized in the same way, I find it very easy to follow.
The first chapter tells you how to download and setup your development environment. You basically need JavaFX SDK and NetBeans IDE. If you have experience on modern IDE like NetBeans or Eclipse, it won’t be difficult for you to install everything. A working development environment speeds up your progress in learning because you can try out the sample code while you are reading the book.
The second chapter provides an overview of JavaFX by an example called GuitarTuner. This example gets you on fast track to understand key concepts in JavaFX, such as declarative syntax, scene graph, binding and animation. After the first two chapters, you will probably get a feel of what functionalities can be achieved by JavaFX and how they are done in the language.

The third chapter is about the language elements, such as variables and types, operators and expressions, classes and objects, functions and triggers. This chapter may seem tedious for experienced programmers. However, these are the fundamentals of a language, so my suggestion is to go through it fast and come back from time to time for language references.
The next two chapters introduce the graphical objects and UI components. You need to know them in order to construct your UI by using nodes, shapes, layouts, skins and SWING wrappers provided by JavaFX. If you know SWING or Java2D well, you may be able to identify some links between JavaFX and Java.
The sixth chapter elaborates on a JavaFX project “Piano” to demonstrate various features to build a rich application. By digesting this example, readers learn how to put everything together to build a JavaFX application. After finishing this chapter, a Java programmer should be able to write applications in JavaFX.

Chapter 7 and 8 illustrate two important features of JavaFX: animation and image handling, which include topics on Timelines, Keyframes, interpolation, path, transition, Image and ImageView classes. If you want your application to get “richer” and have better user experience, you should spend more time on these two chapters.

Chapter 9 gives more details on getting internet data through RESTful web services. Getting remote data is almost a must for any RIA. Readers will learn two classes of JavaFX: PullParser and HttpRequest to retrieve and parse JSON or XML data. An example shows how to invoke web services from flickr’s photo services.
The last chapter describes how to develop a JavaFX mobile application. The Mobile Emulator in NetBeans is introduced. If you are going to develop a mobile application, you should definitely read this chapter to understand some mobile-specific issues. As an example, the authors walk you through the process of migrating a desktop JavaFX program to run on a mobile device.
In general, the content of the book “Essential JavaFX” is easy to be understood and the examples are quite instructive. I think the authors probably aim at writing a textbook for junior or intermediate programmers, hence some advanced features of JavaFX are not covered, such as multi-media and reflection. To sum up, I would recommend it to people who are about to learn the JavaFX language. It helps you learn JavaFX effectively.
P.S. if you are interested in other JavaFX books, you can check out Jonathan Giles’ blog of Mini ‘Pro JavaFX Platform’ Book Review. I may write some comparison of a few JavaFX books too. So check back my blog later.
Nov 28
Posted: under Citizenship.
Tags: america, american, citizen, question, Test, The Citizenship, united states, USNovember 28th, 2009
Last year, the USCIS( United States Citizenship and Immigration Services) had changed the US citizenship test format. This citizenship test is part of the naturalization process for immigrants to get their American citizenship.
The test usually contains two parts. The first part is a test of English skill, which includes reading, writing and speaking English. [...] [...more]
Last year, the USCIS( United States Citizenship and Immigration Services) had changed the US citizenship test format. This citizenship test is part of the naturalization process for immigrants to get their American citizenship.
The test usually contains two parts. The first part is a test of English skill, which includes reading, writing and speaking English. The second part is the civics test, which a USCIS officer asks the applicant 10 questions about the United States. The applicant must answer at least six questions in order to pass this interview exam.
In the new citizenship test, there are 100 possible questions which the USCIS officer may ask. So it is very important that the citizenship applicants practise enough before going for the interview. One of the best citizenship web sites provides a free online citizenship test practcing system. This practice system randomly generates 5-50 questions. It provides very good practice for people to get familiar with the test format and background knowledge.
This web site also provide excellent products such as DIY US citizenship application kit and American immigration application kits for family class. If you understand English, you probably need only these application kits to apply for your citizenship, or help your family members to reside in the United States.
Other Links:
US Citizenship Application and Test Questions
Canadian Citizenship Test Questions
UK Citizenship Online Test
Free Online Canada Citizenship Test
New Citizenship Test Questions of Australia
Life in the UK: British Citizenship Test
US American Citizenship Practice Test
US Citizenship Application Package
Oct 18
Posted: under Citizenship.
Tags: Application, Canadian, citzienship, TestOctober 18th, 2009
Recently, some Canadian friends asked me how to apply for their citizenship in Canada. Here are the advices I gave them:
For one to apply for the Canadian citizenship, there are some basic requirements:
1) be a landed immigrant(permanent resident ) in Canada;
2) be 18 years of age or older at the time of application [...] [...more]
Recently, some Canadian friends asked me how to apply for their citizenship in Canada. Here are the advices I gave them:
For one to apply for the Canadian citizenship, there are some basic requirements:
1) be a landed immigrant(permanent resident ) in Canada;
2) be 18 years of age or older at the time of application submission;
3) have resided in Canada for a total of three years out of the four years on the day before you apply. You may count half of the time for the time you resided in Canada before you became a PR. The time you resided in Canada after you became a permanent resident counts as full time;
4) know enough English or French for a simple conversation; and
5) know enough about Canada’s geography, politics, history, and the rights and responsibilities of a citizenship to pass a test.
If all the above requirements are meet, one can pay the citizenship fees which are $200.00 in total. The fees can be paid at most financial institutions such as a bank. After that, send the application to the CIC case processing center. Things to send in:
a) Receipt of payment of citizienship fees;
b) Completed application form;
c) Two photos taken within the last 12 months.
d) Supporting document such as Permanent Resident Card(Maple Card) and two personal IDs.
Canada Citizenship Test on iphone ipod
Free Online Canada Citizenship Test
Canadian Citizenship Application and Test
New Citizenship Test Questions of Australia
Life in the UK: British Citizenship Test
Online American Citizenship Test
US Citizenship Application
Aug 19
Posted: under JavaFX.
Tags: Application, JavaFX, jnlp, web startAugust 19th, 2009
What does an earthquake have to do with JavaFX? It is not so obvious, eh?
After I published my post about a JavaFX Online Wish Tree Application, I received some emails from readers reporting there were some problems to start the JavaFX client of the wish tree demo. I double checked and found nothing wrong in [...] [...more]
What does an earthquake have to do with JavaFX? It is not so obvious, eh?
|
After I published my post about a JavaFX Online Wish Tree Application, I received some emails from readers reporting there were some problems to start the JavaFX client of the wish tree demo. I double checked and found nothing wrong in my code and the deployment environment. So I provided some hints and started to work with those readers to troubleshoot the problem.
|
|
|
After a few rounds of emails back-and-forth, we finally determined that it was due to a recent earthquake occured near the Taiwan region. The earthquake caused serious damage to the communication cables underneath the Pacific ocean. These cables are backbones connecting the internet between Asia and North America. As a result, people in Asia could not visit almost 70% of web sites located in North America. Still, how was this related to my JavaFX app? Here is the fact: the JNLP file of JavaFX requires connecting to javafx.com every time the application gets launched. Due to the outage of network, users in Asia could not connect to javafx.com. This eventually caused the failure of launching my JavaFX demo.
Since Sun does not allow redistribution of the JavaFX binary code, a user must connect to javafx.com to get some necessary jar files in order to run a JavaFX application. I suppose JavaFX should provide an alternative approach to resolve this kind of issue. Right now, the workaround is to have the javafx jar/dll files uploaded to the web server and modify the JNLP file to include them for the application.
Other JavaFX Articles:
JavaFX Nodes Usded in Swing Apps JavaFX API for Java
Building JavaFX Menu How can Java Code Call JavaFX?
Jul 29
Posted: under JavaFX.
Tags: api, java, JavaFX, swingJuly 29th, 2009
Last week, in a poll many java developers said they did not want to use JavaFX in their applications. A reason is probably that the APIs of JavaFX is not yet stable. It is true that JavaFX language itself is still evolving. If we search on the internet and we often get obsolete examples [...] [...more]
Last week, in a poll many java developers said they did not want to use JavaFX in their applications. A reason is probably that the APIs of JavaFX is not yet stable. It is true that JavaFX language itself is still evolving. If we search on the internet and we often get obsolete examples which no longer run in the latest JavaFX version. So “pay attention to the publishing date” is a useful tip when you are looking for documents on JavaFX.
The second reason that developers stay away from JavaFX is the lack of convenient way to integrate existing Java applications with JavaFX. Undoubtedly, the strength of JavaFX is that it is based on Java. It gets compiled into bytecode, runs on a JVM and it can call methods of java classes. While compared with Flex or Silverlight, JavaFX has the advantage of n million of Java developers and a huge amount of Java applications. This is great and it gives a robust start to JavaFX. Unfortunately, there is no official way(except for reflection) for Java to fully utilize JavaFX features directly. This becomes a substantial barrier for people to adopt JavaFX.
JavaFX’s attraction to Java developers is the functionalities that are not available in Java SE, such as animation, media processing, charting. However, the price may be too high for developers to convert their existing Java code into JavaFX only to leverage the new features. There are many Java applications out there which cannot be easily changed, esp. for enterprise applications. If we have an easy way to call JavaFX functions from Java, the adoption of JavaFX in the Java developer community will be a lot faster and wider.
I think an ideal architecture of JavaFX API may look like this:

I am not sure technically how difficult it is to come up with a JavaFX API for Java, but I think it should be given some consideration for future JavaFX releases. Since JavaFX is still in its early stage of development, I hope we can see something like this sooner rather than later.
Related Articles:
How to Display JavaFX Scene in a Swing Window
Using JavaFX Features in Java
Interoperability between JavaFX & Java
How to Show a SWING Menu in JavaFX
Convert Swing to JavaFX
Jun 20
Posted: under JavaFX, JavaFX Coding.
Tags: Interoperability, java, JavaFXJune 20th, 2009
In my previous post Interoperability between JavaFX and Java, I discussed three possible approaches to invoke JavaFX features from the Java side. These approaches were:
1. The ScriptEngineManager class. It is based on JSR-223, the java scripting API, which allows a java program to call a script(such as JavaFX Script, javascript).
2. The JavaFX reflection API. It [...] [...more]
In my previous post Interoperability between JavaFX and Java, I discussed three possible approaches to invoke JavaFX features from the Java side. These approaches were:
|
1. The ScriptEngineManager class. It is based on JSR-223, the java scripting API, which allows a java program to call a script(such as JavaFX Script, javascript).
2. The JavaFX reflection API. It can probably call any classes in JavaFX.
3. The JavaFX class implements a Java interface so that a Java program can invoke the JavaFX class via the interface. The interface acts as a bridge between the two sides.
|
The third one seems the most elegant to call JavaFX from Java. However, there is a drawback: the program should start from the JavaFX side. The reason is that it is simpler to use JavaFX code to instantiate the JavaFX classes which can be passed to Java code. Nevertheless, in some scenario, it would be better to start the program from the java side. For example, if you want to add in some JavaFX features to an existing large java application, it is better to have java code as the entry point. To solve this issue, I am combining the essence of Approach 2 and 3 to create the below example.
Let’s say we want to invoke the latest charting functions of JavaFX 1.2 from the java code. We will first use the JavaFX reflection API to instantiate the JavaFX class. We then use it via its java interface. So we define a Java interface first.
/*
* JavaInterface.java
*
* @author Henry Zhang http://www.javafxgame.com
*/
package javatest;
public interface JavaInterface {
public void addData(String name, float data);
public void showChart();
}
The next step is to create a JavaFX class MyChart to implements this interface:
/*
* MyChart.fx
*
* @author Henry Zhang http://www.javafxgame.com
*/
package javatest;
import javafx.scene.chart.PieChart;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart3D;
public class MyChart extends JavaInterface {
var chartData : PieChart.Data[] = [];
public override function addData( l:String, v: Number):Void {
var labelString = l;
var data = PieChart.Data {
label : l
value : v
action: function() {
println("{labelString} clicked!");
}
} ;
insert data into chartData;
}
public override function showChart() : Void {
var chart =
PieChart3D {
data : chartData
pieThickness: 25
pieLabelFont: Font{ size: 9 };
pieToLabelLineOneLength: 10
pieToLabelLineTwoLength : 20
pieLabelVisible: true
pieValueVisible: true
translateY: -50
};
Stage {
title: "PieChart Window"
width: 520
height: 300
scene: Scene {
content: [
Text {
font : Font {
size : 16
}
x: 200
y: 20
content: "Pie Chart"
},
chart
]
}
}
}
}
The last thing is to write the java main class JavaTest.
/*
* JavaTest.java
* @author Henry Zhang http://www.javafxgame.com
*/
package javatest;
import javafx.reflect.FXClassType;
import javafx.reflect.FXLocal;
import javafx.reflect.FXLocal.Context;
import javafx.reflect.FXLocal.ObjectValue;
public class JavaTest {
public static void main(String args[]) {
Context context = FXLocal.getContext();
FXClassType instance = context.findClass("javatest.MyChart");
ObjectValue obj = (ObjectValue)instance.newInstance();
JavaInterface ji = (JavaInterface)obj.asObject();
String [] labels = {"January", "Febuary", "March", "April"};
int [] values = { 18, 20, 25, 37 };
for ( int i=0; i < values.length; i++ ) {
ji.addData(labels[i], values[i]);
}
ji.showChart();
}
}
In the above code, there are three lines for instantiating a JavaFX class via reflection:
Context context = FXLocal.getContext();
FXClassType instance = context.findClass("javatest.MyChart");
ObjectValue obj = (ObjectValue)instance.newInstance();
The next line is to convert the JavaFX instance into a java interface so that it can be used by Java code:
JavaInterface ji = (JavaInterface)obj.asObject();
If you are using NetBeans IDE, you can set javatest.JavaTest as the main class in your project properties(so that it can be the entry point of your program). Build this project you will get a javatest.jar. Running this program produces the below screenshot:
To run it from the command line, use the below command:
javafx -jar javatest.jar
Actually, you could do it in the purest java style by including all the JavaFX runtime stuffs, the command would look like this:
java -Djava.library.path="<path to javafx sdk lib>"
-classpath "<all javafx sdk jars>" -jar javatest.jar
Since there are many jar files used by the JavaFX, this purest java approach turns out to be very troublesome. I would rather use the javafx command, which is a wrapper of the above java command.
Please leave comments if you have any questions.
This article is cross-posted at Calling JavaFX Classes from Pure Java Code. The Chinese translation can be found at http://www.javafxblogs.com.
JavaFX Used in Winter Olympic Games 2010
Review on Essential JavaFX
US Citizenship Practice Test
Jun 18
Posted: under JavaFX, JavaFX Coding, Javafx Games.
Tags: 1.2, game, java, JavaFX, widget, widgetfxJune 18th, 2009
To fully take advantage of the power of JavaFX 1.2, Stephen Chin had just released the WidgetFX 1.2 API beta version. There is even a widget contest running until the end of July.
Just before the JavaOne 2009, Jim Weaver asked me to write a widget for my JavaFX Pac-man game. The WidgetFX API was [...] [...more]
To fully take advantage of the power of JavaFX 1.2, Stephen Chin had just released the WidgetFX 1.2 API beta version. There is even a widget contest running until the end of July.
Just before the JavaOne 2009, Jim Weaver asked me to write a widget for my JavaFX Pac-man game. The WidgetFX API was quite simple to use, so I finished it pretty soon. The game widget later got demo-ed on Jim and Steve’s JavaOne sessions. There was a small problem of the pac-man widget: it run relatively slow due to the performance issue of JavaFX 1.1. Since JavaFX 1.2 and WidgetFX 1.2 are ready now, I am modifying the code to see the improvement on performance.
First, the code of the Pac-Man game needs to be modified a little bit for JavaFX 1.2 . Since multi-inheritance is gone, we need to use mixin classes now. You can refer to my articles on insideRIA.com for details of the code. Changes for JavaFX 1.2 were given on comments of Article 4 by Patrick Webster. I also added in a pausing key(”P” button) handling for the game. I compiled the game into a pacman.jar file.
The next step is to write the widget. Actually, the code is quite simple if you do not have stuffs like configuartion etc. Let’s take a look at the code below:
/*
* PacManWidget.fx
* http://www.javafxgame.com
*/
package pacmanwidget;
import org.widgetfx.Widget;
/**
* @author Henry Zhang
*/
def defaultWidth = 528.0;
def defaultHeight = 576.0;
def maze = pacman.Maze {};
var widget:Widget = Widget {
width: defaultWidth
height: defaultHeight
aspectRatio: defaultWidth / defaultHeight
resizable: false
content: maze
onDock: function():Void {
maze.pauseGame();
}
}
return widget;
In the standalone game, an instance of the Maze class was put into the content variable of a Stage. Now, instead of putting it into a Stage, we add it into a Widget. To do this, we can just set the content variable of a Widget instance. Other attributes of the Widget class are quite straightforward, mostly for resizing purposes. The next thing is to write a onDock() function to pause the game when the widget gets docked. The game can be resumed after pressing the “p” button when it is undocked.
The last thing is to deploy it on a web server. We need a JNLP file. Be sure to write the jnlp file of the JavaFX 1.2 style. Netbeans can generate the JNLP file which we can modify for deployment. I listed below part of my jnlp file. Besides the widget code PacManWidget.jar, there are supporting jar files( pacman.jar and WidgetFX-API.jar) under the /lib folder as well. Notice that there is a bug in the generated JNLP file by NetBeans 6.5.1: the <update> tag is missing a slash(/) at the end of the tag.
. . . . . .
<resources>
<j2se version="1.5+" />
<extension name="JavaFX Runtime"
href="http://dl.javafx.com/1.2/javafx-rt.jnlp"/>
<jar href="PacManWidget.jar" main="true"/>
<jar href="lib/pacman.jar"/>
<jar href="lib/WidgetFX-API.jar"/>
</resources>
<application-desc main-class="com.sun.javafx.runtime.main.Main">
<argument>MainJavaFXScript=pacmanwidget.PacManWidget</argument>
</application-desc>
<update check="background" />
. . . . . .
Now, you can click on the below button to start the Pac-man widget for JavaFX 1.2. Enjoy!
Pac-Man Widget 1.2
Pac-Man Game Widget for WidgetFX 1.2
Jun 13
Posted: under JavaFX, JavaFX Coding, Javafx Games.
Tags: game, JavaFX, pac-manJune 13th, 2009
On java.net, there was a post by kfarnham about my articles on writing Pac-man game in JavaFX. He wondered whether there would be a fifth article. The answer is positive. Yesterday, my last article of a series, “Writing the Pac-Man Game in JavaFX Part 5“, had been published on insiderRIA.com. This final article detailed the [...] [...more]
On java.net, there was a post by kfarnham about my articles on writing Pac-man game in JavaFX. He wondered whether there would be a fifth article. The answer is positive. Yesterday, my last article of a series, “Writing the Pac-Man Game in JavaFX Part 5“, had been published on insiderRIA.com. This final article detailed the chasing algorithms of the ghosts. I think it is probably one of the most interesting things in the code.
When writing the game, there are a few points we need to consider before designing an algorithm of the ghosts, such as effectiveness, randomness, simplicity. You can refer to the article about considerations on these aspects. An excerpt from the article is listed below in blue text. It discussed the choice of a proper algorithm. This algorithm not only serves as the chasing logic, it can also control the escaping behavior of the ghosts.
. . . . . .
After some thinking, I found that the distance between a ghost and the Pac-Man is a good ranking metric. The shorter the distance is, the higher the score is given to a particular choice. The advantages of using the distance as a metric are obvious. It is very simple and can be caculated easily. Besides, this algorithm makes a ghost move in the direction that has the shortest distance to thePac-Man. To illustrate this algorithm, let’s look at the below figure.

In the figure, the ghost Blinky is moving into an intersection from the right to the left. When it reaches the intersection, it has three possible choices of its next movement: to go up, to go down and to continue heading left. Going down is not a valid move because it hits the border of the maze. So we need to compare the other two options. The below table shows the computation of the distance of the two possible moves:
| Choice |
X distance |
Y distance |
Total |
| Intersection |
3 |
10 |
13 |
Up |
3 |
9 |
12 |
| Left |
4 |
10 |
14 |
As shown in the table, the distance from the intersection to the Pac-Man character is 13 (The distance between two adjacent dots is 1). If Blinky goes up, the distance is reduced to 12. If it heads left, the distance becomes 14. Therefore, going up seems a better choice for Blinky. In this way, Blinky should be able to get closer and closer to the Pac-Man and eventually catches him.
Of course, this simple algorithm does not take into consideration for the walls in the maze. For this reason, sometimes the calculated score does not in fact represent the shortest path. However, this inaccuracy makes the ghosts appear “stupid” in the game, which is the randomness we want to achieve in the behavior. So we are going to implement it in our code. We rewrite the class MoveDecision. When the function evaluate() calculates a score, it takes in two arguments: the reference to Pac-Man instance and whether the ghost is in a hollow state. The variable distance is used to compute the score. If the ghost is going after the Pac-Man character, the score is 500-distance, which means a shorter distance yields a higher score. If the Pac-Man is hunting the ghosts(when they are hollow), the score is caculated as 500+distance. This makes the ghosts running away from the Pac-Man.
. . . . . .
Now that all the articles had been published and I hope you enjoyed reading them. The game was originally written in JavaFX 1.0, and was compatible with JavaFX 1.1. Because multi-inheritance has been removed in JavaFX 1.2, I made some minor changes to the code. The abstract class MovingObject had been changed to mixin class. The code for JavaFX 1.2 can be download from JavaFX Game Download Page.
You can now click on the below image to play the completed Pac-Man game, it is based on the newly released JavaFX 1.2 . With the improved performance, the game run very smoothly.

Related Articles:
JavaFX Pac Man Part 5
Develop Games in JavaFX
JavaFX MineSweeper Demo Game
JavaFX Demo Game: LinkUP
WidgetFX Game Widgets: Pac-Man
My First JavaFX Game Demo
JavaFX Discussion Blogs
The Featured Articles on insideRIA.com:
May 14, 2009: Writing the Pac-Man Game in JavaFX - Part 1
May 21, 2009: Writing the Pac-Man Game in JavaFX - Part 2
May 28, 2009: Writing the Pac-Man Game in JavaFX - Part 3
June 4, 2009: Writing the Pac-Man Game in JavaFX - Part 4
June 11, 2009:Writing the Pac-Man Game in JavaFX - Part 5
Jun 06
Posted: under JavaFX, JavaFX Coding, Javafx Games.
Tags: articles, game, JavaFX, pac-manJune 6th, 2009
My latest article of a series, “Writing the Pac-Man Game in JavaFX Part 4“, was out on June 4. As we continue on bulding the game, the articles are getting more and more interesting now.
In this fourth article, the interaction between Pac-Man character and the four ghosts was implemented. The article showed how to determine [...] [...more]
My latest article of a series, “Writing the Pac-Man Game in JavaFX Part 4“, was out on June 4. As we continue on bulding the game, the articles are getting more and more interesting now.
In this fourth article, the interaction between Pac-Man character and the four ghosts was implemented. The article showed how to determine whether the Pac-man character and a ghost touched each other. A simplified equation was applied to achieve better performance. When Pac-man touches a ghost, he can eat it if the ghost is hollow. The ghost then is thrown back to the cage again. Otherwise, the ghost eats the Pac-man, at this moment, an animation of showing a dying Pac-Man appears. This is in fact a shrinking circle which disappears at the end of the animation. The animation is accomplished by the DyingPacMan class.
The below figure depicts the animation process of the dying Pac-man character.

The code of DyingPacMan.fx is listed below:
public class DyingPacMan extends Arc {
var timeline = Timeline {
repeatCount: 1
keyFrames: [
KeyFrame {
time: 600ms
action: function() {
// hide the pacMan character & ghosts before the animation
maze.pacMan.visible = false;
for ( g in maze.ghosts ) {
g.hide();
}
visible = true;
}
values: [ startAngle => 90, length=>360 ];
},
KeyFrame {
time: 1800ms
action: function() {
visible = false;
}
values: [ startAngle => 270 tween Interpolator.LINEAR,
length => 0 tween Interpolator.LINEAR ]
},
]
}
... code omitted ...
}
As you can see it in the code, there are two keyframes of the animation. Interpolations of two instance variables, startAngle and length, are involved during the animation. To better illustrate this process, the below figure shows the change of the shape against a timeline. The animation started with a pause of 600ms and then the first key frame appears, which is a full circle. After that, the full circle will gradually turns into nothing(empty circle). This effect is done by the interpolation provided by JavaFX API.
Hope you enjoy reading the articles. You can use arrow keys to play the current version of the game. The ghosts are moving randomly which makes the game less challenging. In the next article, I will introduced a better algorithm. Try it by clicking the below screenshot:

Related Articles:
More articles on JavaFX Games: Developing Games in JavaFX
Source of the Pac-Man Game
JavaFX Demo Game: MineSweeper
JavaFX Demo Game: LinkUP
Game Widgets for WidgetFX: Pac-Man
My JavaFX Demo Game: Pac-Man
May 31
Posted: under JavaFX, JavaFX Coding, Javafx Games.
Tags: demo, example, game, JavaFX, pacmanMay 31st, 2009
The latest JavaFX article of writing the Pac-Man game is published on May 28. It is the third out of a five-article series: “Writing the Pac-Man Game in JavaFX - Part 3“.
In this article, the ghosts are introduced. The animation of the ghosts are almost the same as the Pac-Man character. It is basically [...] [...more]
The latest JavaFX article of writing the Pac-Man game is published on May 28. It is the third out of a five-article series: “Writing the Pac-Man Game in JavaFX - Part 3“.
In this article, the ghosts are introduced. The animation of the ghosts are almost the same as the Pac-Man character. It is basically moving a CustomNode and switching the images. There are three sets of images for the animation: normal, hollow and flashing. The moving algorithm of the ghosts is the heart of the code. In this article, for simplicity, a random moving algorithm is applied. A more complicated moving behavior of the ghosts will be introduced in Article 5. Click on the below image to try the program so far. The Pac-man and ghosts cannot eat each other even they meet in the maze. The feature of eating each other will be illustrated in next article. As before, you can try this semi-completed program by clicking Java Web Start button below:

Related Articles:
My JavaFX Demo Game: Pac-Man
Articles on Writing the JavaFX Pac-Man Game
Pac-Man Game WidgetFX Widget
JavaFX Game Example Code: MineSweeper
JavaFX Game Demo Example: Pac-Man
Other unrelated links:
Applicant of American Citizenship Information, software and guide.
Guide American Citizenship in United States
Canadian Citizenship Application and Practice Exam
May 21
Posted: under JavaFX, JavaFX Coding, Javafx Games.
Tags: JavaFX, pac-manMay 21st, 2009
The 2nd article of the series, “Writing the Pac-Man Game in JavaFX“, is published today.
The first article introduced a data model in Java and the JavaFX drawing logic of the maze. In the 2nd article, the animation part of the Pac-Man character is detailed. When you are reading, you can click on the java [...] [...more]
The 2nd article of the series, “Writing the Pac-Man Game in JavaFX“, is published today.
The first article introduced a data model in Java and the JavaFX drawing logic of the maze. In the 2nd article, the animation part of the Pac-Man character is detailed. When you are reading, you can click on the java web start links to see the Pac-Man opening and closing mouths, and gradually moving inside the maze. The keyboard handling code is illustrated as well.
Some JavaFX features demostrated in these two articles include:
. shapes
. keyboard handling
. animation timeline
. java code integration
. Transfromation
Hope you can enjoy reading the articles. You can use arrow keys to play a no-ghost version of the game. The Pac-Man character now can move around and gobble dots. Try it by clicking the below screenshot:


Related Articles:
Develop Games in JavaFX
My JavaFX Demo Game: Pac-Man
May 16
Posted: under JavaFX, JavaFX Coding, Javafx Games.
Tags: articles, game, JavaFX, pac-manMay 16th, 2009
After the release of JavaFX 1.0, I wrote a Pac-Man game using the JavaFX API. Many people were quite interested in the game. They either enjoyed playing it or asked me for the details fo the JavaFX code. JavaFX expert Jim Weaver invited me to write some articles about the process of building the [...] [...more]
|
After the release of JavaFX 1.0, I wrote a Pac-Man game using the JavaFX API. Many people were quite interested in the game. They either enjoyed playing it or asked me for the details fo the JavaFX code. JavaFX expert Jim Weaver invited me to write some articles about the process of building the game. After a few weeks’ hard work, with Jim’s constructive ideas and great help in proofreading, I finished the articles. Now they are published on insideRIA.com, an O’Reilly’s web site, as featured articles. There will be 5 articles in total and they will run through the coming 5 weeks.
|
|
In each article, there are a few web start links that you can click on and start a JavaFX program to see how it works. If you follow the 5 articles, you will find out how the game is built bit by bit. I hope the articles can help people who want to learn JavaFX or want to develop games in JavaFX. Thanks Jim for making these articles possible. My thanks also goes to Rich, the editor of insideRIA.com.
Here is the links for the articles:
May 14, 2009:
Writing the Pac-Man Game in JavaFX - Part 1
May 21, 2009:
Writing the Pac-Man Game in JavaFX - Part 2
May 28, 2009:
Writing the Pac-Man Game in JavaFX - Part 3
June 4, 2009:
Writing the Pac-Man Game in JavaFX - Part 4
June 11, 2009:
Writing the Pac-Man Game in JavaFX - Part 5
Related articles:
Answer: Blinky, Pinky, Inky and Clyde from Jim Weaver’s Blog
My JavaFX Demo Game: PACMAN
JavaFX Demo Game: PAC-MAN
May 14
Posted: under JavaFX, JavaFX Coding.
Tags: JavaFX, wish treeMay 14th, 2009
This is a JavaFX program for my kids, or say it is some fun for everybody. You can make a wish and put it somewhere on a Wish Tree. Hopefully, it will come true some time pretty soon. A star hanging on the tree denotes a wish. For Phase I, I am building this wish [...] [...more]
This is a JavaFX program for my kids, or say it is some fun for everybody. You can make a wish and put it somewhere on a Wish Tree. Hopefully, it will come true some time pretty soon. A star hanging on the tree denotes a wish. For Phase I, I am building this wish tree as a standalone application. In Phase II, I will make an internet version, so that everyone can place wishes on the same tree(s).
When you click on the wish tree, a wish star appears and a dialog is shown to allow you to enter your name and your wish. Later on, if you click on the same star, you have a chance to modify your wish. My daughter likes it very much, she places all kinds of wishes( such as I want a Barbie) on the tree and really hope they will come true soon. Go have some fun by clicking on the below image to place your wishes and good luck! ( JDK1.5+ is required, JDK 1.6 U13+ is better):


The program utilizes the features of JavaFX effect classes. The source code can be downloaded here. I will write a few articles to explain how to create such an application.
The article is also posted at javafxgame.com: JavaFX Wish Tree.
May 02
Posted: under JavaFX.
Tags: highlighter, JavaFX, keywords, reserved, syntax, wordsMay 2nd, 2009
Recently, when I was writing some articles on JavaFX, I found it necessary to obtain a list of reserved words(keywords) of JavaFX so that I could use them in a syntax highlighter for blogs and web pages. After some search, I found them at [...more]
Recently, when I was writing some articles on JavaFX, I found it necessary to obtain a list of reserved words(keywords) of JavaFX so that I could use them in a syntax highlighter for blogs and web pages. After some search, I found them at openjfx site. Since the keywords may be useful for other purposes, I list them below ( for JavaFX 1.1):
abstract after and as assert at attribute before bind bound break
catch class continue def delete else exclusive extends false finally
first for from function if import indexof in init insert instanceof
into inverse last lazy mixin mod new not null on or override
package postinit private protected public-init public public-read
replace return reverse sizeof static step super then this throw
trigger true try tween typeof var where while with
Here is a sample of the JavaFX syntax highlighter, if you are intersted, check it out here: JavaFX syntax highlighter.
package pacman;
import java.lang.Math;
import pacman.MazeData;
import pacman.PacMan;
/**
* @author Henry Zhang
*/
public class MoveDecision {
// x and y of an intended move
public var x: Number;
public var y: Number;
// evaluate if the move is valid and its score if it's valid
public function evaluate(pacMan:PacMan, isHollow:Boolean): Void {
if ( x < 1 or y < 1 or y >= MazeData.GRID_SIZE
or x >= MazeData.GRID_SIZE){
score = -1;
return ;
}
}
. . .
}
Apr 28
Posted: under Citizenship.
Tags: Canadian, Citizenship, online, practice, TestApril 28th, 2009
After a few weeks’ hard work, I finally came up with an Online Practice for the Canadian Citizenship Test. Many of my friends are Canadians and they find my online practice system very interesting and helpful.
This online system has a database of more than 120 practice questions. What makes it different from other systems [...] [...more]
After a few weeks’ hard work, I finally came up with an Online Practice for the Canadian Citizenship Test. Many of my friends are Canadians and they find my online practice system very interesting and helpful.
This online system has a database of more than 120 practice questions. What makes it different from other systems is that it contains province-specific questions. For example, for citizenship applicants in Ontario, the questions will be like “What is the Premier of Ontario?”. This system can also keep track of practicing time and give a score based on the number of correct answers. After the test taker finishes a practice test, he/she can re-do the test for more practice.
So far, more than 400 daily visitors use this online practice system. I am very happy with it and will continue to work on it for improvement. More on Canadian Citizenship Practice Exam .
Apr 20
Posted: under JavaFX.
April 20th, 2009
Now that Oracle agrees to buy Sun for $7.4B. The acquisition of Sun has finally come to an end( or at least for a while). When we comparing the deal with IBM, it seems a better result for Sun, which is one of the most innovative companies in the Silicon Valley. Unlike IBM’s overlapping product [...] [...more]
Now that Oracle agrees to buy Sun for $7.4B. The acquisition of Sun has finally come to an end( or at least for a while). When we comparing the deal with IBM, it seems a better result for Sun, which is one of the most innovative companies in the Silicon Valley. Unlike IBM’s overlapping product lines, most of Sun’s software and hardware products are complement to Oracle’s. It is definitely a good news for Java, because now a software company owns it and should be able to make better use of it.
The future of JavaFX may not look so optimistic. JavaFX is only a few months old(since officially released). The APIs are not stable yet. It is not an industry standard and not many vendors are committed to it. Further, competing technology such as Flash is very popular and almost dominates the RIA domain. The only advantage of JavaFX is the broad user base of Java language. JavaFX is indeed built on top of Java, this makes it the biggest reason to use JavaFX. If Sun is acquired by Oracle, the roadmap or vision of JavaFX may change, or lay some uncertainty ahead.
If the acquisition does go through, I do hope Oracle can continue to foster JavaFX, which is still in its infancy.
Apr 08
Posted: under JavaFX, Javafx Games.
Tags: frozen bubble, game, JavaFXApril 8th, 2009
Liu Xuan, a Chinese programmer, had written a Frozen Bubble game in JavaFX. He is kind to allow me to share his code here. The game was originally developed in Perl/SDL. A java port is available too. Liu’s program implemented a simplified version of the Frozen Bubble game in JavaFX.
Click on the below button to [...] [...more]
Liu Xuan, a Chinese programmer, had written a Frozen Bubble game in JavaFX. He is kind to allow me to share his code here. The game was originally developed in Perl/SDL. A java port is available too. Liu’s program implemented a simplified version of the Frozen Bubble game in JavaFX.
Click on the below button to start the game, use left/right arrow key to aim and space button to fire.


The key handling code is accomplished in the class Container:
public class Container extends CustomNode{
public var bubbles = new HashMap();
public var fadeBubbles: Bubble[];
public var fallBubbles: Bubble[];
public var gun: Gun = Gun{};
public var shootAngle: Number;
public var group: Group = Group {
content: [
// backgroud
Rectangle {
width: 320
height: 480
strokeWidth: 1
stroke: Color.BLACK
fill: LinearGradient {
startX: 0.0,
startY: 0.0,
endX: 0.0,
endY: 1.0
proportional: true
stops: [ Stop {
offset: 0.0
color: Color.YELLOWGREEN },
Stop {
offset: 1.0
color: Color.LIGHTBLUE } ]
}
onKeyPressed: function(e: KeyEvent):Void {
// keyboard event handling
.......
}
}
gun
//warning line
Line {
startX: 0,
startY: Config.RED_LINE
endX: 320
endY: Config.RED_LINE
strokeWidth: 1
stroke: Color.RED
}
ImageView {
.......
}
]
};
public var inverseX = 1;
//semi-transparent layer for game over screen
var layer = Rectangle {
width: 320
height: 480
fill: Color.BLACK
opacity: .4
}
var text = Text {
content: "Press Enter To Start"
font: Font {
size: 20
}
x: 60
y: 250
}
// status of the game
// 0 - game start and wait for shooting
// 1 - bubble is moving
// 2 - game over, the animation timeLine instanc
// will stop at this value
public var state = 2 on replace {
if(state == 2) {
timeline.stop();
insert layer into group.content;
insert text into group.content;
}
}
override public function create(): Node {
group
}
public function getLocation(row: Integer, col: Integer) : Point{
var locationY = Config.ROW_SPACE * row;
var locationX;
if(row mod 2 == 0) {
locationX = Config.BUBBLE_DIAMETER * col
} else {
locationX =
Config.BUBBLE_DIAMETER * (col + .5) as Integer
}
return new Point(locationX, locationY)
}
public function getAround(row: Integer, col: Integer): Bubble[] {
var bArray: Bubble[] = [];
var flag: Integer = 0;
if(row mod 2 == 0) {
flag = -1;
}
var bubble0 = getBubble(row, col - 1);
var bubble1 = getBubble(row - 1, col + flag);
var bubble2 = getBubble(row - 1, col + 1 + flag);
var bubble3 = getBubble(row, col + 1);
var bubble4 = getBubble(row + 1, col + flag);
var bubble5 = getBubble(row + 1, col + 1 + flag);
insert bubble0 into bArray;
insert bubble1 into bArray;
insert bubble2 into bArray;
insert bubble3 into bArray;
insert bubble4 into bArray;
insert bubble5 into bArray;
return bArray;
}
public function getAround(bubble: Bubble): Bubble[] {
var row: Integer = bubble.index.x;
var col: Integer = bubble.index.y;
return getAround(row, col);
}
public function getSameBubble(bubble: Bubble): Vector {
var vector: Vector = new Vector();
vector.add(bubble);
var cursor = 0;
while(
cursor < vector.size()) {
var bubbleInVector: Bubble =
vector.get(cursor++) as Bubble;
var aroundBubbles:Bubble[]=getAround(bubbleInVector);
for(aroundBubble in aroundBubbles) {
if ( aroundBubble != null
and aroundBubble.color == bubble.color
and vector.indexOf(aroundBubble) == - 1) {
vector.add(aroundBubble);
}
}
}
return vector;
}
public function getConnected(bubble: Bubble): Vector {
var vector: Vector = new Vector();
vector.add(bubble);
var cursor = 0;
while(cursor < vector.size()) {
var bubbleInVector: Bubble =
vector.get(cursor++) as Bubble;
var aroundBubbles:Bubble[]=getAround(bubbleInVector);
for(aroundBubble in aroundBubbles) {
if ( aroundBubble != null
and vector.indexOf(aroundBubble) == - 1) {
vector.add(aroundBubble);
}
}
}
return vector;
}
public function getIsolatedBubble(vector: Vector): Vector {
var islatedBubble: Vector = new Vector();
for(object in vector) {
var sameBubble: Bubble = object as Bubble;
var aroundBubbles:Bubble[] = getAround(sameBubble);
for(aroundBubble in aroundBubbles) {
if(aroundBubble != null) {
var connectedBubble:Vector=getConnected(aroundBubble);
var islate = true;
for(col in [0..= 3) {
for(object in vector) {
var sameBubble: Bubble = object as Bubble;
bubbles.remove(sameBubble.index);
insert sameBubble into fadeBubbles;
}
for(object in getIsolatedBubble(vector)) {
var islatedBubble: Bubble = object as Bubble;
bubbles.remove(islatedBubble.index);
insert islatedBubble into fallBubbles;
}
}
state = 0;
checkGameOver();
}
}
var timeCount = 0;
//moving, erasing, dropping the bubbles
def timeline = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames:[
KeyFrame {
time: 0.005s
action: function() {
......
checkGameOver();
.......
//reduce the transparency to erase the bubbles
for(fadeBubble in fadeBubbles) {
fadeBubble.opacity -= .02;
if(fadeBubble.opacity <= 0) {
fadeBubble.visible = false;
delete fadeBubble from fadeBubbles;
delete fadeBubble from group.content;
}
}
//drop those isolated bubbles
for(fallBubble in fallBubbles) {
fallBubble.locationY += 5;
if(fallBubble.locationY >= 428) {
fallBubble.visible = false;
delete fallBubble from fallBubbles;
delete fallBubble from group.content;
}
}
if(state == 1) {
......
//rebounce and collision handling
checkCollision(bubble);
}
}
}
]
}
// initialization
public function gameStart():Void {
.....
timeline.play();
}
}
Source code can be downloaded here. Please note that Liu Xuan has the copyright of the code.