1 2 3 Previous Next


39 posts

After JavaOne Blog

Posted by malenkov Oct 20, 2011

Recently, I visited the JavaOne conference held by Oracle. I was a speaker at the BOF session named "Embed HTML in Your JavaFX 2.0 Application". To my big surprise, only 15 visitors came. It would be interesting to hear their opinion, since this is my first experience of presenting in English. Despite this, I will publish several articles to promote the material from my session.

I really enjoyed the organization of the conference. Awesome! It was very interesting to meet colleagues with whom I communicated only through e-mail. It turned out that it is much easier to meet my friends from St. Petersburg in San Francisco, though we are living and working in one city.


Reversy Ataxx Blog

Posted by malenkov Oct 21, 2010

My colleague has developed a totally new game on a hexagonal board. At the moment, the only one game set is available. While he together with his friends is perfecting their skills, we would like to create an implementation of this game for PC. I suggested that we use my implementation of the Minimax algorithm. To demonstrate its simplicity and flexibility, I created an Ataxx clone slightly modifying my Reversy game.

You can find the source code of the application here. However, for a start, I recommend you to distinguish between the Reversy and Ataxx implementations. The first difference is that I do not calculate the weights of the pieces on the Ataxx board by default. The second difference is that the move consists of two phases: choosing the piece and choosing its new position. Although the calculation depth for the Ataxx game is 2, I cannot win this algorithm.

Hopefully, I'll find some time to clear up the source code of the game.

Stay tuned!

I developed my first implementation of the Reversi game on BASIC 20 years ago. Since then, I ported it on each programming language I studied: Turbo Pascal with graphics library and Turbo Vision, C with the Windows API, C++ with the ClanLib, Java AWT applet, and Swing application with Java2D. Now I am ready to publish yet another implementation, on JavaFX Script.

This game allows to compete with one of the algorithms as well as to see how these algorithms compete with each other. The Sergey algorithm is based on the Minimax algorithm with a simple table of game piece weights where the calculation depth is 6. The Pavel algorithm is developed by my colleague, and I have got it from the official JavaFX site. But I had to add the following constructor:

public Board(GameBoard board) {
    Object dark = board.getFriend();
    Object light = board.getEnemy();
    int pos = 11;
    for (int y = 0; y < 8; y++, pos += 2) {
        for (int x = 0; x < 8; x++, pos++) {
            Object piece = board.getPiece(x, y);
            this.data[pos] = (piece == dark)
                ? PIECE_DARK
                : (piece == light)
                    ? PIECE_LIGHT
                    : PIECE_EMPTY;
    this.movePiece = PIECE_DARK;

When I increased the calculation depth, I discovered that the search function started blocking the UI. The rationale is that the Timeline class invokes all functions from key frames on the thread which renders UI. I decided to override the abstract JavaTaskBase class and implement the RunnableFuture interface to avoid extra entities:

public class JavaTask extends JavaTaskBase, RunnableFuture {
  override function create() {
  override function run() {
    // do something

However, I found out that the RunnableFuture interface must be implemented on Java, i.e. it is prohibited to use FX objects. It seems to me that in this case the JavaTaskBase class should not be an abstract class. It should be initialized via a public variable as in my JavaTask class:

public class JavaTask extends JavaTaskBase {
  public-init var runnable: RunnableFuture on replace {

  override function create() {

Note that JavaFX does not support thread synchronization. Be careful!

If you know how to use the invokeLater method of the EventQueue class to split a long tasks, you can use the deferAction method of the FX class in the same way. This method invokes a function on the thread which renders the UI. Thus, you don't need synchronization in this case.

Also Baechul's Weblog will be useful.

original post


Attentiveness Evaluation Blog

Posted by malenkov Jul 15, 2010

The attentiveness evaluation test in my driving school was easier than one I developed by using JavaFX. I made it harder by adding the next value randomly.

The test data are stored in the PersistentProperties class that combines the Storage and the Properties classes. When you create its instance, all the key-value pairs are loaded from the specified storage. This class provides utility methods to convert a string value into the expected type. For example,

  public function getInteger(key, default: Integer) {
    var value = get(key);
    if (value != null) try {
      return Integer.parseInt(value)
    catch (exception) {

This method takes a string value for a given key and tries to parse it as an Integer value. If the value is not found or it could not be parsed, the method returns the default value. I think, it might be helpful to have such utility methods in the Properties class. The PersistentProperties class is used in this test as well as in the previous one. The application model based on this class is used to store the data when they are changed. Study the PersistentModel class in detail.

public class PersistentModel {
  def properties = PersistentProperties {
    source: "properties.txt"

First, the data storage is initialized.

  public var misses = properties.getInteger("misses", 0) on replace {
    if (isInitialized(blocker)) {
      properties.put("misses", misses);

Then the misses variable of the Integer type is declared. Note that when you change this variable, its new value is stored in the repository. The following simple method is designed to avoid overwriting the repository during class initialization. The blocker variable is declared as the last variable. It is not initialized during the initialization of other variables. So, during the initialization of the misses variable, the isInitialized(blocker) method returns false. Instead of the blocker variable, it is possible to use any class variable that is declared after this one.

  public-read var passes = properties.getInteger("passes", 0);

The passes variable is declared with the public-read modifier and changes only within the PersistentModel class. Its all changes are made by the model, so that it is possible to omit the 'on replace' block.

  public-read var millis: Long;
  var millisAll = properties.getLong("millis", 0) on replace {
    if (passes > 0) {
      millis = millisAll / passes

The millis variable is used for the average time. However, it is necessary to know all the spent time and the number of the passed attempts to calculate it. Therefore, the auxiliary millisAll variable is declared and the average time is recalculated when it is changed.

  public-read var errors: Long;
  var errorsAll = properties.getLong("errors", 0) on replace {
    if (passes > 0) {
      errors = errorsAll / passes

The errors variable is used similar to the millis variable.

  public function pass(millis: Long, errors: Long) {
    properties.put("passes", ++passes);
    properties.put("millis",   millisAll += millis);
    properties.put("errors",   errorsAll += errors);

The pass function is used to change several variables simultaneously and to store their new values in the storage.

  var blocker = true;

Note that using JavaFX storages solves the problem with the unsigned JNLP applets, that I discovered earlier.

original post

Last half a year I was quite busy. My personal priority was to get a driving license. Among many exercises in my car driving school there was a psychological test consisting of different tasks to check your reaction. I developed one of them by using JavaFX. It examines how fast you can click.

I would like us to consider some localization issues by using my application as an example (see the main script and its russian properties). If a double hash sign ## is prefixed to a string literal, JavaFX substitutes the string literal with a localized one during running the application. It means that the localized strings will be selected from the fxproperties files for the current locale.

For example, for the following JavaFX string literal:

##"Average time"

an fxproperties file could contain the following declaration:

"Average time"="??????? ?????"

It is very convenient and reminds me the gettext library. However, if these string literals are too long, then the fxproperties files become difficult to maintain. JavaFX solves this problem by using shortcuts.

For example, for the following JavaFX string literal:

##[ABOUT]"Click and wait.\nClick again when color is changed"

an fxproperties file could contain the following declaration:

"ABOUT" = "???????? ? ?????.\n??? ????????? ????? ???????? ?????"

These shortcuts could be used for more complex parameterized strings as well.

For example, for the following JavaFX string literal:

"\n{%5d model.misses} misses;"
"\n{%5d model.passes} passes."

an fxproperties file could contain the following declaration:

"FAILED" = "%s:\n%5d ??? ?????????;\n%5d ??? ??????."

Note that variable names are not used in localization. It is important only to declare their types. You can reorder variables using the following notation: %[index$]type.

And the most important feature! While in Java SE you had to use native2ascii converter, JavaFX enables you to change the charset using the following command:

@charset "windows-1251";

It allows to create the fxproperties files in your favorite editor, even if it does not support UTF. This feature is very relevant for me.

JavaFX fxproperties files are much more convenient and more powerful than Java SE properties files. For more information, see the tutorial and the language reference.

original post

Caching of an empty array is a well-known pattern to improve performance. However, it is difficult to use it in generified classes.

Out of curiosity, I created a custom implementation of the array creation method based on Array.newInstance. To cache empty arrays, I use synchronized WeakHashMap, which maps any given component type to a weak reference to the corresponding empty array. This is not the fastest way, but it does not lead to memory leaks.

private static final Map<Class<?>, Reference<?>> map =
         new WeakHashMap<Class<?>, Reference<?>>();

public static <T> T[] newInstance(Class<T> type,
                                        int length,
                                        boolean cache) {
    if (!cache || length != 0) {
        return (T[]) Array.newInstance(type, length);
    synchronized (map) {
        Reference<?> ref = map.get(type);
        Object array = (ref == null) ? null : ref.get();
        if (array == null) {
            array = Array.newInstance(type, length);
            map.put(type, new WeakReference(array));
        return (T[]) array;

Note that the method returns an array of a given type. I used the SuppressWarnings annotation to suppress warnings about unchecked casts.

Consider the results of the test application. The left column shows the number of iterations. During each iteration, an empty array is created for every given component type. The middle column shows the average time of an empty array creation. The right column shows the average time of creating and retrieving the shared empty array. Frankly, I was surprised that the caching of a single array is slower than caching of several ones.

AttemptsAverage time (ns)
      1 490 65676
     10 490   1813
    100 388    961
   1000 392    980
  10000 248    223
100000 274     56

1 class per attempt

AttemptsAverage time (ns)
      1 262 2278
     10 261    69
    100 247    64
   1000 262    63
  10000 257    61
100000 258    62

88 different classes per attempt

Cached empty arrays can be useful for the JVM too. For example, when calling varargs methods without arguments a new empty array is created every time. I do not think that anyone expects such behavior.

What do you think?


Along the River Blog

Posted by malenkov Nov 19, 2009

Dodecahedron Blog

Posted by malenkov Oct 26, 2009

Scores in detail Blog

Posted by malenkov Oct 6, 2009

Score your game Blog

Posted by malenkov Aug 3, 2009

In a game the score refers to the amount of points gained by a player or a team. Consider a JavaFX component that shows the score and enables its smooth changing.

The value variable of the Score class starts a timeline on replace that smoothly changes the old value to a new one. The width and height variables define a size of a character cell. The score representation depends on the radix variable that is 10 by default. Additionally, you can provide custom images for every digit by using the images variable. In that case, the radix variable will be automatically recalculated. If you do not want to create custom images you can use the creator function. It should create nodes to insert into the component. Note that the Score class is implemented to display right-to-left oriented numbers, so that new digit orders are added to the left.

Look at the Main class that shows how to use the score counter. The following code creates the binary representation with the default font settings:

Score {
  radix: 2
  width: 15
  height: 6

The following code creates the octal representation with the images:

Score {
  width: 30
  height: 45
  images: for (i in [0..7]) Image {
    url: "{__DIR__}{i}.png"

The following code uses colored text nodes for every digit:

Score {
  def color = for (hue in [36..360 step 36]) Color.hsb(hue, .9, .9);
  creator: function(index) {
    Text {
      content: "{index}"
      fill: color[index]
      font: Font {
        name: "Arial Bold"

Now look at the buttons. I used the Tile container to arrange them. This container automatically resizes nodes that implement the Resizable interface. However, it doesn't resize the buttons created by my custom wrapper of the Button class. To make my wrapper resizable I implemented the following methods:

class MyButton extends CustomNode, Resizable {
  def button = Button {
    width: bind width
    height: bind height
  override function create() {
  override function getPrefHeight(width) {
  override function getPrefWidth(height) {

original post


FX Mobilization Blog

Posted by malenkov Jun 17, 2009

My Preferences Blog

Posted by malenkov Jun 4, 2009

The JavaFX 1.2 SDK provides many useful utility classes such as the Properties class used to access and store name/value pairs or the Storage class used to store the data locally on the client system.


So far the JavaFX programming language does not support hash tables to store data of any type, but you can always use the Properties class for this purpose. For a start, let's create methods to put and get numbers. For example,

  public function put(key: String, value: Number) {
    put(key, value.toString())

  public function get(key: String, default: Number) {
    var value = get(key);
    if (value != null) try {
      return Number.valueOf(value)
    catch (exception) {

Note that the put method converts a number into a string and the get method tries to convert a string into a number. For primitive data types, this is done rather easily. For more complex cases, you can develop your own implementation of the Converter interface and use it to convert an object into a string and vice versa. Let it be your homework exercise.

Now add an ability to store properties automatically. I decided that at the moment of initialization, the class should read all properties from the storage and put them back when an application terminates. This task is very simple.

  var storage: Storage;

  postinit {
    storage = Storage {
      source: source
    if (storage.resource.readable) {

  function store() {
    if (storage.resource.writable) {

Consider an example of how to use the Preferences class. Create a simple application that stores the position and size of a window. Launch this application. Move the window, resize it and then close the application. Launch the same application again. You see that the window is located where you left it in the previous session. It is convenient, isn't it?

class PersistentStage extends Stage {
  def preferences = Preferences {
    source: "bounds"
  } on replace {
    def s = Screen.primary.visualBounds;
    width  = preferences.get("W", s.width  / 2);
    height = preferences.get("H", s.height / 2);
    x = preferences.get("X", s.minX + (s.width  - width)  / 2);
    y = preferences.get("Y", s.minY + (s.height - height) / 2);
  override var x      on replace {preferences.put("X", x     )}
  override var y      on replace {preferences.put("Y", y     )}
  override var width  on replace {preferences.put("W", width )}
  override var height on replace {preferences.put("H", height)}

Later I will improve the Application class from the previous post by adding a support for properties storage.

original post

So the next version of JavaFX has been released. I developed an example that shows all the node-based UI controls that had been added to the API to replace the controls based on the Swing library. Note, that new UI controls are available on all platforms including mobile.

The following set of the controls is included in the current API:
TextBox: A control which displays and accepts input of text.
Button: A simple command button control.
ToggleButton: A control that possesses the ability to be selected.
RadioButton: A kind of a toggle button that has another appearance.
CheckBox: A tri-state selection control with a tick mark when checked.
Hyperlink: An HTML like text label that responds to rollovers and clicks.
Slider: A control that enables selecting a value by sliding a knob.
ProgressBar: A component used to show the progress of a task.
ProgressIndicator: A component that displays the progress in a form of a pie chart.
ListView: A simple list of items that can be editable.
ScrollBar: An element that enables the graphical content of a container to be scrolled.

You can learn more about these controls in the Powerful UI Capabilities With Node-Based Controls tutorial. This article discusses some performance aspects of the UI controls implementation and suggests how to employ them in your applications. First, run this example.

ScrollPane and performance

As you may see, the main window does not contain a scroll bar. However, you can see it in action in the ScrollPane class that supports a mouse wheel. The values of the boundsInParent variable defined in the Node class should be used in expressions to lay out the content. Never bind these values directly! The rational is that these values are updated many times per second and regular recalculations of expressions substantially decrease performance of your application. In order to resolve this problem, I created the Bounds class. The coordinates and dimensions are updated only when the corresponding values actually changed. If you compile and run the application by using the Bounds class, you will see that the values with the prefix content are constantly updated, even if the values are not changed. Another recommendation is to remove println, because the debug printing decreases performance as well.


Games often require to show all the graphical content constantly. That's why, I developed the ScalePane class for these purposes. It is constructed similar to the ScrollPane class and preserves the aspect ratio. Try this example to explore it in action. In some rare cases you might want to disable preserving the aspect ratio, however, run this example to ensure that is looks ugly.


Having reviewed a lot of samples, I realized that each model of the application deployment requires specific actions. All the possible actions are implemented in the Application class. The application not only looks and works identically on the mobile device and in the full-screen mode, but additionally, it enables dragging the applet from a browser without pressing the Alt key. The main class of the example is very simple now.

Application {
  title: "JavaFX Controls"
  header: ImageView { ... }
  background: LinearGradient { ... }
  content: ScrollPane {
    background: Color.WHITE
    border: 10
    content: ...

Refer to the source code of the Controls class for more infromation.



Don't miss this Blog

Posted by malenkov Apr 12, 2009

Filter Blog

By date: