Jan 25 2012

JavaFX 2.* for Linux is coming…

Yeah. Finally:

http://blogs.oracle.com/javafx/entry/javafx_2_0_is_cross

Download:

http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html

I think I will take a closer look in a few days…


Jul 6 2010

JavaFX2Java Bridge added to JFXtras (step 2)

Thanks to Stephen: He has prepared a branch for the upcoming 0.7 release of JFXtras. Now it has been possible to merge the latest changes to the JFXtras default branch.

There are a lot of changes waiting in line. While the 0.7 release will be a huge step, I am really looking forward for 0.8…

So if you want to take a look at the latest changes, just check out the source code at http://code.google.com/p/jfxtras/source/checkout.


Jul 3 2010

JavaFX2Java Bridge added to JFXtras (step 1)

It has taken a long time since I promised to integrate the JavaFX2Java bridge to JFXtras until I finally did it…

At the moment the code is located at a clone that will be integrated as soon as JFXtras 0.7 has been released.

The clone can be accessed there:

https://js-mavenization.googlecode.com/hg/

The package is named “org.jfxtras.bridge”.


Jun 18 2010

JFXtras: 0.7 RC1 released

Hi guys,

the first release candidate for JFXtras 0.7 has been released. This version is (should be) fully functional with JavaFX 1.3
Downloads can be found at http://jfxtras.org/


May 11 2010

Closing the gap between Java and JavaFX

There is a huge gap between Java and JavaFX: While it is very easy to bind JavaFX objects to each other there has been no way to bind JavaFX objects to Java properties (and vice versa).

It has taken me some time to figure out how this could be solved. And at the moment I am in the progress of adding that stuff to the JFXtras project.
This will take some time until I have taken all necessary steps.

Until then i want to give you a quick jar that can be used to try that stuff…

To try it, download that jar and add it to the classpath of your JavaFX project:
bridge-1.0.0-SNAPSHOT-jar-with-dependencies

There are two ways of synchronization. At first it is possible to listen for changes to Java objects and update an JavaFX object accordingly. At the moment I have implemented two ways to listen for updates.

Java to JavaFX

  • PropertyChangeEvents: This is the recommended way: Just make your Java bean fire PropertyChangeEvents whenever a property has changed.
  • Busy waiting: I have added a hackish way of busy waiting. This should not be used in production code. But it offers a fast way to test things

JavaFX to Java

The reverse way has also two ways implemented:

  • Calling of setters: If a JavaFX var is updated, this bridge calls the corresponding setter of your Java object (using reflection or optionally your own optimized implementation).
  • PropertyChangeEvents: It is possible to create a bridge that converts the JavaFX binding
    updates to PropertyChangeEvents.

With inverse…

Of course it is also possible (and most of the time necessary) to create bindings with inverse. I give you a small sample how this might work here:

We create our Java “model”:
[cc lang="java"]package fxbindingtest;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class JavaClass {
private float amount = 99;

public float getAmount() {
return amount;
}

public void setAmount(float amount) {
pcs.firePropertyChange(“amount”, this.amount, this.amount=amount);
System.out.println(“Changed amount to ” + amount );
}

final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

public void addPropertyChangeListener( PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener( PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
}
[/cc]

And here comes our JavaFX stage. This stage contains just a slider that is bound to the Java object (with inverse).
Every five seconds the model object is updated (amount+=10) – and reflected by the slider.

[cc lang="c"]package fxbindingtest;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import com.cedarsoft.fx.JavaFxBridge;
import com.sun.javafx.runtime.FXObject;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;

/**
* @author johannes
*/
var slider: Slider;

//The java model class. Contains the property “amount” and a PropertyChangeSupport
def javaModel = new JavaClass();

Stage {
title: “Application title”
scene: Scene {
width: 800
height: 600
content: [
slider = Slider {
min: 1
max: 100
snapToTicks: true
}
]
}
}

//Create the binding from the java model to the slider
//Using the defaults:
// Java –> FX: PropertyChangeEvents
// FX –> Java: Calling setters by reflection
JavaFxBridge.bridge( javaModel ).to( slider as FXObject ).connecting(
JavaFxBridge.bind( “amount” ).to( “value” ).withInverse()
); //sorry for the stupid API – needs some polishing…

//Add a timeline to simulate changes to the model
Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
KeyFrame {
time: 5s
action: function() {
println("changing amount on model");
javaModel.setAmount( javaModel.getAmount() + 10 );
}
}
];
}.play();
[/cc]

And here a JNLP to run the demo (open Java Console to see the updates printed to System.out):
webstart

Disclaimer:
This is just a working-in-some-situations-prototype. It is not production-ready by far.
But if you have any comments/ideas/bugs, please mail me.

The source code can be downloaded here. But I will add that stuff to JFXtras very soon…


May 8 2010

Binding PropertyChangeSupport to JavaFX objects transparently

Binding is one of the best features in JavaFX. The possibility to class Java APIs from JavaFX is another one.
But unfortunately there is no easy way to combine JavaFX binding and Java PropertyChangeEvents. Therefore I have taken a look at the JavaFX code and I think I have found a possible solution:

The manual way

Of course you can add on replace triggers on every var and fire your events manually:
[cc lang="c"]
class Customer{
public var name:String = “” on replace old {
pcs.firePropertyChange(“name”, old, name );
};
public var address:String = “” on replace old {
pcs.firePropertyChange(“address”, old, address );
};
public var mail:Email on replace old {
pcs.firePropertyChange(“mail”, old, mail );
};
public-read def pcs = new PropertyChangeSupport( this );
}
[/cc]

This has at least three disadvantages:

  • At first your code becomes very ugly. A lot of boilerplate code without any type checking. Very easy to make faults. Very hard to find them.
  • But the second problem is even worse – if you don’t know for sure whether there is a listener registered. This approach destroys lazy binding which has been introduced in JavaFX 1.3. Every time the binding is invalidated, the replace trigger forces an update – even if nobody is registered at the PropertyChangeSupport.
  • It can’t be “attached” to existing JavaFX classes.

Using an automated bridge

I have created a bridge that can be attached to every JavaFX object. This bridge uses the JavaFX binding stuff and translates the binding updates to PropertyChangeEvents.
There is no reflection involved when vars are updated (just when setting it up). So performance shouldn’t be a problem.
(Of course this approach also prevents lazy bindings since the events have to be created every time the vars change). So only attach the bridge if it is necessary.

The bridge can be used like that:
[cc lang="java"]
* FXObject fxObject = …
* Fx2PropertyChangeEvent bridge = Fx2PropertyChangeEvent.bindProperties( “name”, “id” ).to( fxObject );
* bridge.addPropertyChangeListener( “name”, new PropertyChangeListener(){…} );
[/cc]

Of course the bridge can also be used within your JavaFX scripts/classes.

And here comes the code: Feel free to use it:

[cc lang="java"]
package com.cedarsoft.fx;

import com.sun.javafx.runtime.DependentsManager;
import com.sun.javafx.runtime.FXBase;
import com.sun.javafx.runtime.FXObject;
import com.sun.javafx.runtime.annotation.Public;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;

/**
* This is a bridge that connects a PropertyChangeSupport to one or more JavaFX vars.
*

* This bridge does use reflection only to set things up! Whenever a var is updated there no(!) reflection is used!
* Therefore the performance is quite good.
*

*

* The Code might look like that:
*

 * FXObject fxObject = ...
 * Fx2PropertyChangeEvent bridge = Fx2PropertyChangeEvent.bindProperties( "name", "id" ).to( fxObject );
 * bridge.addPropertyChangeListener( "name", new PropertyChangeListener(){...} );
 * 

*/
@Public
public class Fx2PropertyChangeEvent extends FXBase {
@NotNull
private final PropertyChangeSupport pcs;
@NotNull
private final List entries = new ArrayList();
@NotNull
private final FXObject bindee;

public Fx2PropertyChangeEvent( @NotNull FXObject bindee ) {
this( bindee, null );
}

public Fx2PropertyChangeEvent( @NotNull FXObject bindee, @Nullable PropertyChangeSupport pcs ) {
super( false );
this.bindee = bindee;
this.pcs = pcs == null ? new PropertyChangeSupport( this ) : pcs;
initialize$( true );
}

/**
* Convert to property change events.
*
* @param propertyName the name of the property (var)
*/
void bindTo( @NotNull String propertyName ) {
try {
String fieldName = “$” + propertyName;
bindee.getClass().getField( fieldName );
} catch ( Exception ignore ) {
throw new IllegalArgumentException( “Invalid property name <" + propertyName + ">” );
}

try {
String varNumFieldName = “VOFF$” + propertyName;
Integer varNumField = ( Integer ) bindee.getClass().getField( varNumFieldName ).get( null );

int index = addEntry( propertyName, varNumField );
DependentsManager.addDependent( bindee, varNumField, this, index );
} catch ( Exception e ) {
throw new RuntimeException( e );
}
}

@Override
public boolean update$( FXObject src, int depNum, int startPos, int endPos, int newLength, int phase ) {
Entry entry = getEntry( depNum );
if ( phase == 65 ) {
Object oldValue = src.get$( entry.getVarNumField() );
entry.setOldValue( oldValue );
} else if ( phase == 92 ) {
Object newValue = src.get$( entry.getVarNumField() );
pcs.firePropertyChange( new PropertyChangeEvent( src, entry.getPropertyName(), entry.getOldValue(), newValue ) );
} else {
throw new IllegalStateException( “Invalid phase: ” + phase );
}

super.update$( src, depNum, startPos, endPos, newLength, phase );
return true;
}

private int addEntry( @NotNull @NonNls String propertyName, int varNumField ) {
int index = entries.size();
entries.add( new Entry( propertyName, varNumField ) );
return index;
}

@NotNull
private Entry getEntry( int depNum ) {
return entries.get( depNum );
}

public void addPropertyChangeListener( PropertyChangeListener listener ) {
pcs.addPropertyChangeListener( listener );
}

public void removePropertyChangeListener( PropertyChangeListener listener ) {
pcs.removePropertyChangeListener( listener );
}

public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener ) {
pcs.addPropertyChangeListener( propertyName, listener );
}

public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener ) {
pcs.removePropertyChangeListener( propertyName, listener );
}

@NotNull
public FXObject getBindee() {
return bindee;
}

@NotNull
public PropertyChangeSupport getPcs() {
return pcs;
}

public static class Entry {
private final String propertyName;
private final int varNumField;
private Object oldValue;

public Entry( String propertyName, int varNumField ) {
this.propertyName = propertyName;
this.varNumField = varNumField;
}

public String getPropertyName() {
return propertyName;
}

public int getVarNumField() {
return varNumField;
}

public Object getOldValue() {
return oldValue;
}

public void setOldValue( Object oldValue ) {
this.oldValue = oldValue;
}
}

/**
* Binds the given property names
*
* @param propertyNames the property names
* @return the fluent factory used to create a Fx2PropertyChangeEvent
*/
@NotNull
public static FluentFactory bindProperties( @NotNull @NonNls String… propertyNames ) {
return new FluentFactory( propertyNames );
}

/**
* Binds the given property names
*
* @param propertyNames the property names
* @return the fluent factory used to create a Fx2PropertyChangeEvent
*/
@NotNull
public static FluentFactory bind( @NotNull @NonNls String… propertyNames ) {
return bindProperties( propertyNames );
}

/**
* Fluent factory implementation
*/
public static class FluentFactory {
@NotNull
private final String[] propertyNames;

private FluentFactory( @NonNls @NotNull String[] propertyNames ) {
//noinspection AssignmentToCollectionOrArrayFieldFromParameter
this.propertyNames = propertyNames;
}

/**
* Binds the property names to the given bindee
*
* @param bindee the bindee the properties are bound to
* @return the bridge
*
* @noinspection InstanceMethodNamingConvention
*/
@NotNull
public Fx2PropertyChangeEvent to( @NotNull FXObject bindee ) {
if ( propertyNames.length == 0 ) {
throw new IllegalArgumentException( “Need at least one property to bind to” );
}

Fx2PropertyChangeEvent bridge = new Fx2PropertyChangeEvent( bindee );
for ( String propertyName : propertyNames ) {
bridge.bindTo( propertyName );
}
return bridge;
}
}
}

/**
* Copyright (C) cedarsoft GmbH.
*
* Licensed under the GNU General Public License version 3 (the “License”)
* with Classpath Exception; you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cedarsoft.org/gpl3ce
* (GPL 3 with Classpath Exception)
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 only, as
* published by the Free Software Foundation. cedarsoft GmbH designates this
* particular file as subject to the “Classpath” exception as provided
* by cedarsoft GmbH in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 3 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
* or visit www.cedarsoft.com if you need additional information or
* have any questions.
*/

[/cc]

I will upload a complete project very soon (Monday). This will contain several samples and unit tests….


May 8 2010

JavaFX Internals Part 2

Yesterday I wrote about some JavaFX Internals…. Today comes the second part.

Today we start to use some of the JavaFX classes by Java. Therefore I just added all JavaFX jars to the classpath.

Extending FXBase

It is a very good idea to extend FXBase. We just have to figure out which methods have to be called for initialization. Following the samples, our class could look like that:

[cc lang="java"]
import com.sun.javafx.runtime.FXBase;
import com.sun.javafx.runtime.FXObject;
import com.sun.javafx.runtime.annotation.Public;

@Public
public class Run extends FXBase implements FXObject {
public static void main( String[] args ) {
System.out.println( “Starting!” );

System.out.println( “Finished” );
}

public Run() {
this( false );
initialize$( true );
}

public Run( boolean paramBoolean ) {
super( paramBoolean );
}
}[/cc]

Approaching that binding stuff

As mentioned yesterday the magic happens within the DependentsManager. Thankfully that sources are available…
One key is the WeakBinderRef that can be stored within each FXObject and be retrieved calling getThisRef$internal$().
There is a static method that creates those refs lazyly: WeakBinderRef.instance().

This WeakBinderRef contains the dependencies for this object. The field bindees contains a chain of Dep instances. Interestingly the WeakBinderRef for test does not contain any bindees as one might have expected. Those are the reverse dependencies!

The “real” dependencies are stored within each object within the field DepChain$internal$ (of type DepChain).
Relevant is the bindeeVarNum. Here is the var num stored that dependency is based upon.

Process of dependency notification

Whenever a var is changed, there are two calls made to notifyDependents$. They can be distinguished by the phase (argument).
That methods uses the DependentsManager to call invalidate on all depending objects. Those simply change the flag so that the next time the var is accessed, it can be resolved again.

While the binding performance in JavaFX is much better in 1.3 it is still not really lazy. There happen a lot of calls until the value is marked as invalid.
So I assume that the performance has just been increased for complex binding expressions. Just binding one var to another shouldn’t be much faster now (this is just an assumption!)…

Adding dependencies manually

Now we try to add a dependency manually. It is possible by simply calling “DependentsManager.addDependent()“.
Of course it does not have any visible effects (besides that the update/invalidate methods are called). Because the values are fetched from the original objects… But the debugger shows us, that it is possible to use that bind mechanism from Java.


May 5 2010

Analyzing JavaFX

Today I wanted to analyze the internals of JavaFX. This post is the documentation – primarily made for myself. But maybe useful for somebody else, too…

Simple class

At first I tried to create a simple class with just one var of type String:

[cc lang="c"]public class Test{
var value:String = “asdf”;
}[/cc]

And then I tried to take a look at the internals. Of course I did not decompile that stuff. Instead I used javap and Reflection to analyze it myself. The result could look like that:

[cc lang="java"]
import com.sun.javafx.runtime.FXBase;
import com.sun.javafx.runtime.FXObject;
import com.sun.javafx.runtime.annotation.Public;
import com.sun.javafx.runtime.annotation.ScriptPrivate;
import com.sun.javafx.runtime.annotation.SourceName;

@Public
public class Test extends FXBase implements FXObject {
@ScriptPrivate
@SourceName( “value” )
private String $value;

public Test() {
this( false );
initialize$( true );
}

public Test( boolean paramBoolean ) {
super( paramBoolean );
this.$value = “asdf”;
}
}[/cc]

So, what is interesting about this?
At first the name of the field is not so nice. Very hard to access using Reflection… But probably that is intended.
Every JavaFX class extends FXBase (or implement FXObject if extending another Java class).

Well, those information can be found within the sources of FXBase (look at src.zip)…

Changing var to def

What is the difference? There is just an annotation (@Def) added to the field…
Continue reading


May 1 2010

JavaFX: Template for resizable CustomNode

Creating a CustomNode is very easy. A template is unnecessary. But when this CustomNode shall be Resizable things start to become a little bit more complicated.

Therefore I have created a template that can be used:

[cc lang="c"]
public class MyCustomNode extends CustomNode, Resizable {
override var width on replace { requestLayout() }
override var height on replace { requestLayout() }
override var layoutBounds = bind BoundingBox {
width: this.width
height: this.height
}

init {
children =[
Rectangle {
width: bind width
height: bind height
}
]
}

override function getPrefWidth( number ) {
//return your pref width – hard coded values are ok for most cases
}

override function getPrefHeight( number ) {
//return your pref height – hard coded values are ok for most cases
}

/*
//It is not absolutly necessary to override those methods, but strongly recommended.
override function getMaxWidth() {
//Return the max width
}

override function getMaxHeight() {
//Return the max height
}

override function getMinWidth() {
//Return the min width
}

override function getMinHeight() {
//Return the min height
}*/
}
[/cc]

There is a post containing a template for CustomControls here.


May 1 2010

JavaFX: Making a CustomNode resizable

Creating a CustomNode is quite easy. There are no gotchas, extending CustomNode and adding some children is enough.
But of course that node is not resizable…

So this post shows what is necessary to create a CustomNode that extends Resizable. We follow the same setting: The custom node is placed within a Stack.

Step 1: Extending Resizable

Resizable enforces us to implement the getPrefWidth/Height methods. We just return some hard coded values and try to find out what happens:
The width/height of the CustomNode are set to the values returned by getPrefWidth/Height. But the boundsInLocal and layoutBounds don’t respect that. They still just depend on the children.

Step 2: Requesting Layout

The doc of Resizable tells us that we have to call requestLayout() every time the width/height of the node is changed. Doing this doesn’t make any difference in this context (within a Stack). But when placed in other layouts this is necessary!

[cc lang="c"]
override var width on replace { requestLayout() }
override var height on replace { requestLayout() }
[/cc]

Step 3: Connecting layoutBounds to width/height

As we have learned when looking at CustomControls it is a very good idea to bind the layoutBounds to the width/height. This is necessary to avoid difficult layout bugs that will only occur in some situations and are very hard to track down.

[cc lang="c"] override var layoutBounds = bind BoundingBox {
minX: 0
minY: 0
width: this.width
height: this.height
}
[/cc]

Now the layoutBounds fit to the width/height of the Node. But of course the sizes of the rectangle(s) are still independent. And the boundInLocal don’t fit them neither.

Step 4: Children depend on width/height

Now we connect the width/height of the children to the width/height of our CustomNode.
Now the three values (width/height, layoutBounds, boundsInLocal) correspond correctly with each other.

Important: As mentioned before it is necessary that width/height always correspond with the layoutBounds. Always! But the boundsInLocal may be different from them (larger or smaller) but have to be influenced by them.