<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaFX News, Demos and Insight // FX Experience &#187; API Design</title>
	<atom:link href="http://fxexperience.com/category/api-design/feed/" rel="self" type="application/rss+xml" />
	<link>http://fxexperience.com</link>
	<description>Sharing the Experience of JavaFX</description>
	<lastBuildDate>Fri, 03 Feb 2012 22:47:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Worker Threading in JavaFX 2.0</title>
		<link>http://fxexperience.com/2011/07/worker-threading-in-javafx-2-0/</link>
		<comments>http://fxexperience.com/2011/07/worker-threading-in-javafx-2-0/#comments</comments>
		<pubDate>Sat, 02 Jul 2011 23:49:15 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=1281</guid>
		<description><![CDATA[For the past couple of years the industry has continued to follow Moore&#8217;s Law by shifting from CPU clock speed to increasing the number of cores and threads per core. Even cell phones are getting multiple cores these days! Taking advantage of all these cores and threads is one of the hallmarks of modern GUI [...]]]></description>
			<content:encoded><![CDATA[<p>For the past couple of years the industry has continued to follow <a href="http://en.wikipedia.org/wiki/Moore's_law">Moore&#8217;s Law</a> by shifting from CPU clock speed to increasing the number of cores and threads per core. Even <a href="http://www.engadget.com/2010/12/15/lg-optimus-2x-first-dual-core-smartphone-launches-with-android/">cell phones</a> are getting multiple cores these days! Taking advantage of all these cores and threads is one of the hallmarks of modern GUI platforms. But all this concurrency brings a multitude of problems to the application developer, not least of which is that writing multithreaded applications is <em>hard!</em></p>
<p>In designing JavaFX 2.0, we of course needed to address both how the scene graph would behave in the presence of multiple threads, and how developers could effectively do work in background threads and keep the UI responsive. In short, the JavaFX scene graph, like all other mainstream GUI toolkits, is not thread-safe and must be accessed and manipulated from the UI thread (call the FX Application thread). Swing and AWT had the same basic policy (only work with Swing or AWT from the Event Dispatching Thread), as did SWT (only interact with SWT resources and components from the thread that owns them), as do all other major toolkits (JavaScript / HTML included).</p>
<p>The most common problem with this design is that developers who do not do work on background threads invariably create unresponsive applications, since this long lived (potentially blocking) code happens on the same thread that processes user events. That is, while your long lived operation is running, no mouse or key events are being processed, which leads to an application that appears to &#8220;hang&#8221;.</p>
<p>Further, actually writing well behaved background workers is difficult and error prone. Even if you create a Runnable and create a Thread and do your long-lived work in that background thread, at some point you need to communicate back to the UI, either with the result of the long-lived computation, or by communicating to a ProgressIndicator of some kind what the progress of this long-lived operation is. This is error prone, because you must be sure to communicate with the UI by putting events back onto the event queue (using Platform.runLater, the equivalent of Swing&#8217;s invokeLater).</p>
<p><em>Note: This article is a sneak peek at a new API which is coming in the next couple of weeks, but is not currently available in the Beta builds! There is a deprecated Task class in the beta builds which will be removed and replaced with the one detailed here.</em></p>
<p>Suppose we have a simple background thread which just counts from 0 to 1 million. Suppose I have a single ProgressBar, and that I need to update the progress of this ProgressBar as the counter runs. A naive implementation might look like this:</p>
<pre class="brush: java; title: ; notranslate">
final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
        for (int i=1; i&lt;=1000000; i++) {
            final int counter = i;
            Platform.runLater(new Runnable() {
                @Override public void run() {
                    bar.setProgress(counter/1000000.0);
                }
            });
        }
    }
}).start();
</pre>
<p>This is a hideous hunk of code, a crime against nature (and programming in general). First, you&#8217;ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables &#8212; a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.</p>
<p>Java comes with a very complete set of concurrency libraries in the java.util.concurrent package. We wanted to leverage what was already defined in Java, but we needed to extend these APIs to take into account the FX Application thread and the constraints that GUI programmers are under. The javafx.concurrent package contains three core files: Worker, Task, and Service.</p>
<p>Before diving into the rather verbose description (taken from the proposed javadocs) for Worker, Task, and Service I wanted to cut to the chase and show some examples. The first key thing to mention, is that Worker is an interface that is implemented by both Task and Service, and which adds the sort of convenience API necessary for a background worker that is useful for communicating back with a UI. Second, Task extends from java.util.concurrent.FutureTask. This means that a Task can very cleanly fit into the concurrent libraries. As you may know, FutureTask implements Runnable, and can be passed to an Executor&#8217;s execute() method.</p>
<p>So real quick, here is the same example as above, but it suffers from none of the flaws exhibited in the naive implementation.</p>
<pre class="brush: java; title: ; notranslate">
Task task = new Task&lt;Void&gt;() {
    @Override public Void run() {
        static final int max = 1000000;
        for (int i=1; i&lt;=max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
</pre>
<p>In this example, I first create my Task. The task implementation just does its work, invoking the protected <code>updateProgress</code> method defined on Task, which ends up updating progress, totalWork, and workDone properties on the Task. I then create my ProgressBar and bind its progress property with the progress property of the Task. Then, since Task is a Runnable, I can just create a new Thread passing it the Task and then start the Thread.</p>
<p>Alternatively, I could create an Executor or ExecutorService (such as a ThreadPoolExecutorService) and <code>execute</code> the task using the ExecutorService.</p>
<p><span id="more-1281"></span></p>
<p><b><i>Edit July 11, 2011: I have updated the API slightly since this post was originally written, and I&#8217;ve updated the post to reflect the current names. In particular, the &#8220;progress&#8221; property is now a value between 0 and 1 (or -1), matching the &#8220;progress&#8221; property on ProgressIndicator and other parts of the platform. &#8220;workDone&#8221; and &#8220;totalWork&#8221; are used to indicate the total units of work to do (such as bytes to be downloaded) and the total units of work that have been done (such as the bytes that have been downloaded). I&#8217;m not totally jazzed by the names, but felt it was important for &#8220;progress&#8221; to mean the same thing on Worker and ProgressIndicator.</i></b></p>
<p>Below are some further descriptions taken from the javadocs.</p>
<h2>Worker</h2>
<p>A Worker is an object which performs some work in one or more background threads, and who&#8217;s state is observable and available to JavaFX applications and is usable from the main JavaFX Application thread. This interface is primarily implemented by both Task and Service, providing a common API among both classes which makes it easier for libraries and frameworks to write user interfaces with observable workers.</p>
<p>A Worker may, or may not be reusable, depending on the implementation. A Task, for example, is not reusable while a @link Service is.</p>
<p>A Worker has a well defined life cycle. Every Worker begins in the READY state. When the Worker has been scheduled for work (for example, when a Service&#8217;s start() method is called), it is transitioned to SCHEDULED. Even Workers which are not technically scheduled, but started immediately (such as with Task#run()) will transition through SCHEDULED on its way to the  RUNNING state.</p>
<p>When the Worker is actually performing its work, the state will have been transitioned to RUNNING. If the Worker completes normally, it will end in the SUCCEEDED state, and the result of the Worker will be set as the <code>value</code> property. If however an Exception occurs during the execution of the Worker, then the state will be set to FAILED and the <code>exception</code> property will be set to the Exception which occurred.</p>
<p>At any time prior to the conclusion of the Worker (that is, if the state is not already SUCCEEDED or FAILED) the developer may invoke the Worker#cancel() method. If called, the Worker will cease execution (if possible, including use of Thread.interrupt) and the state changed to CANCELLED.</p>
<p>The only valid beginning state for a Worker is READY, and the valid ending states are CANCELLED, SUCCEEDED, and FAILED. The <code>running</code> property is set to true when the state is either SCHEDULED or RUNNING.</p>
<p>The Worker&#8217;s progress can be monitored via three different properties, <code>workDone</code>, <code>totalWork</code>, and <code>progress</code>. These properties are set by the actual implementation of the Worker interface, but can be observed by anybody. The <code>workDone</code> is a number between -1 (meaning indeterminate progress) and <code>totalWork</code>, inclusive. When <code>workDone == totalWork</code> the <code>progress</code> will be 100% (or 1). <code>totalWork</code> will be a number between -1 and Long.MAX_VALUE, inclusive. The progress will be either -1 (meaning indeterminate), or a value between 0 and 1, inclusive, representing 0% through 100%.</p>
<p>A Worker which is in the READY or SCHEDULED states will always have <code>workDone</code> and <code>progress</code> set to -1. A Worker which is in the SUCCEEDED state will always have <code>workDone == totalWork</code> and <code>progress == 1 or -1</code>. In any other state, the values for these properties may be any value in their respective valid ranges.</p>
<h2>Task</h2>
<p>A fully observable implementation of a FutureTask. Tasks exposes additional state and observable properties useful for programming asynchronous tasks in JavaFX, as defined in the Worker interface. An implementation of Task must override the Task#call() method. This method is invoked on the background thread. Any state which is used in this method must be safe to read and write from a background thread. For example, manipulating a live scene graph from this method is unsafe and will result in runtime exceptions.</p>
<p>Tasks are flexibly and extremely useful for the encapsulation of work. Because Service is designed to execute a Task, any Tasks defined by the application or library code can easily be used with a Service. Likewise, since Task extends from FutureTask, it is very easy and natural to use a Task with the java concurrency java.util.concurrent.Executor API. Finally, since a Task is Runnable, you can also call it directly (by invoking the Task#run() method) from another background thread. This allows for composition of work.</p>
<p>Although java.util.concurrent.ExecutorService defines several methods which take a Runnable, you should generally limit yourself to using the <code>execute</code> method inherited from java.util.concurrent.Executor.</p>
<p>As with FutureTask, a Task is a one-shot class and cannot be reused. See Service for a reusable Worker.</p>
<p>Because the Task is designed for use with JavaFX GUI applications, it ensures that every change to the public properites, as well as change notifications for state, errors, and for event handlers, all occur on the main JavaFX application thread. Accessing these properties from a background thread will result in runtime exceptions being raised.</p>
<h2>Service</h2>
<p>A Service is a non-visual component encapsulating the information required to perform some work on one or more background threads. As part of the JavaFX UI library, the Service knows about the JavaFX Application thread and is designed to alieviate the application developer from the burden of manging multithreaded code that interacts with the user interface. As such, all of the methods and state on the Service are intended to be invoked exclusively from the JavaFX Application thread.</p>
<p>Service implements {@link Worker}. As such, you can observe the state of the background operation and optionally cancel it. Service is a reusable Worker, meaning that it can be reset and restarted. Due to this, a Service can be constructed declarativley and restarted on demand.</p>
<p>If an java.util.concurrent.Executor is specified on the Service, then it will be used to actually execute the background worker. Otherwise, a daemon thread will be created and executed. If you wish to create non-daemon threads, then specify a custom Executor (for example, you could use a ThreadPoolExecutor).</p>
<p>Because a Service is intended to simplify declarative use cases, subclasses should expose as properties the input parameters to the work to be done. For example, suppose I wanted to write a Service which read the first line from any URL and returned it as a String. Such a Service might be defined, such that it had a single property, <code>url</code>. It might be implemented as:</p>
<pre class="brush: java; title: ; notranslate">
public class FirstLineService extends Service {
    private StringProperty url = new StringProperty();
    public final void setUrl(String value) { url.set(value); }
    public final String getUrl() { return url.get(); }
    public final StringProperty urlProperty() { return url; }

    protected Task createTask() {
        final String _url = getUrl();
        return new Task&lt;InputStream&gt;() {
            protected String call() {
                URL u = new URL(_url);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(u.openStream()));
                String result = in.readLine();
                in.close();
                return result;
            }
        }
    }
 }
</pre>
<h2>Conclusion</h2>
<p>We anticipate that libraries of Tasks, both specialized for your specific application and also general libraries of Tasks will be developed over time that perform common operations such as downloading files, performing HTTP form submits, copying files, uploading files, sorting, doing statistical analysis, and so forth. These reusable bodies of code can then be combined together, used with thread pools or other rich executor services, and used with Services.</p>
<p>Let us know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2011/07/worker-threading-in-javafx-2-0/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>New to JavaFX 1.3: Cells</title>
		<link>http://fxexperience.com/2010/04/new-to-javafx-1-3-cells/</link>
		<comments>http://fxexperience.com/2010/04/new-to-javafx-1-3-cells/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 12:05:18 +0000</pubDate>
		<dc:creator>Richard Jasper and Jonathan</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Controls]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=644</guid>
		<description><![CDATA[In JavaFX 1.3 a lot of work has gone into ListView, and extracting out the base virtualization engine (the secret sauce to high performance lists) such that it is able to be used in controls such as TreeView and TableView. At the same time we wanted to make it really easy for developers to customize [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaFX 1.3 a lot of work has gone into ListView, and extracting out the base virtualization engine (the secret sauce to high performance lists) such that it is able to be used in controls such as TreeView and TableView. At the same time we wanted to make it really easy for developers to customize what is shown in each ListView row. What we&#8217;ve ended up doing is creating the concept of a cell, which at any point in time represents at most one item in your ListView, and it is through the cell that you have total freedom about how to display your data. Finally, as noted, we&#8217;ve expanded this concept to also be used in exactly the same way in TreeView (which is a preview in JavaFX 1.3), and it is likely to also underpin any future TableView control.</p>
<p><span id="more-644"></span>The ListView and TreeView controls support a huge number of items, but the &#8216;cost&#8217; of having the control actually visually represented is only what you see on screen. Of course, there is also the cost of simply having the data lying around (which is not really in the domain of the control to handle &#8211; needless to say &#8211; be smart <img src='http://fxexperience.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ). In other words, we are very smart about not creating nodes for list items that aren&#8217;t actually visible, and about updating the cell content based on user interactions such as scrolling and keyboard navigation. Also, each cell is reused, rather than being created and thrown away as necessary for each individual item in the ListView.</p>
<p>Of course, the other part of our job is to make easy to use API&#8217;s, so we&#8217;ve worked hard on this aspect as well. By default when you put an item into a ListView, we create a simple String-based cell that shows the text in the cell when necessary. In other words, if all you&#8217;re wanting is the same output as what you saw in JavaFX 1.2, you don&#8217;t need to change anything. On the other hand, if you want a more fancy ListView, that is where the concept of a cell factory comes into play. You can see a cell factory on a ListView control, and then whenever the ListView needs to update (because the visible items change), the cellFactory is consulted and you&#8217;re responsible for populating the cell as appropriate.</p>
<p>Prior to showing off the code, it would be useful to quickly summarize our key design goals, so that you&#8217;ll hopefully better understand why we did things the way we did. Our goals were the following:</p>
<ul>
<li>Both time and memory efficient for large data sets</li>
<li>Easy to build and use libraries for custom cells</li>
<li>Easy to customize cell visuals</li>
<li>Easy to customize display formatting (12.34 as $12.34 or 1234% etc)</li>
<li>Easy to extend for custom visuals</li>
<li>Easy to have &#8220;panels&#8221; of data for the visuals</li>
<li>Easy to animate the cell size or other properties</li>
</ul>
<p>Right, now definitely seems like a good time to actually show off some code. As a first example, if I were to create a custom cell which formatted numbers such that they would appear as currency types, I might do so like this:</p>
<pre class="brush: javafx; title: ; notranslate">
import javafx.scene.control.*;

ListView {
    items: [1.23, 3.33, 4.83, 5.32, 6.32]
    cellFactory: function() {
        def cell:ListCell = ListCell {
            node: Label {
                text: bind if (cell.empty) then &quot;&quot; else &quot;${%(,.2f cell.item as Number}&quot;
            }
        }
    }
}
</pre>
<p>In this example the cellFactory is a simple function which returns a ListCell who&#8217;s node content is a Label. The text of that Label is <em>bound</em> to the cell&#8217;s item. Whenever the item associated with a Cell is changed (which might happen if the user scrolls and the cell is reused to represent some different item in the ListView), then the Label&#8217;s text is automatically updated. In addition, if the cell is &#8220;empty&#8221; (meaning it is used to fill out space in the ListView but doesn&#8217;t have any data associated with it), then we just use the empty String.</p>
<p>Cell factories are really very powerful. The custom cells that are created can be anything from simple strings to full blown panels with movies and any other arbitrary content. They can change their size dynamically, and they can be styled easily from CSS.</p>
<p>We make it extraordinarily simple in JavaFX to change the color of cells. Each cell can be styled directly from CSS. So for example, if you wanted to change the default background of cells in a ListView to be a bit more interesting  you could do the following CSS:</p>
<pre class="brush: css; title: ; notranslate">
.list-cell {
   -fx-padding: 3 3 3 3;
   -fx-background-color: honeydew;
}
</pre>
<p>If you run an application with this style, you will notice that not all cells use this new color, only half of them. The other half (as it turns out, the odd numbered rows) are styled by a different rule in CSS which also needs to be specified:</p>
<pre class="brush: css; title: ; notranslate">
.list-cell:odd {
    -fx-background-color: mistyrose;
}
</pre>
<p>Yikes! Looks like a crazy pair of socks. Clearly Jasper was not involved in picking the colors for this posting <img src='http://fxexperience.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>If you wanted to set the color of selected ListView cells to be yellow, you could add this to your CSS file (yikes, the result is truly fearsome!):</p>
<pre class="brush: css; title: ; notranslate">
.list-cell:filled:selected:focused, .list-cell:filled:selected {
    -fx-background-color: yellow;
    -fx-text-fill: black;
}
</pre>
<p>Each of these examples require no code changes. Simply update your CSS file to alter the colors. You can also use the &#8220;hover&#8221; and other pseudoclasses in CSS the same as with other controls.</p>
<p>Suppose you had a sequence of Numbers to display in a ListView and wanted to color all of the negative values red and all positive or 0 values black. One way to achieve this is with a custom cellFactory which changes the styleClass of the Cell based on whether the value is negative or positive:</p>
<pre class="brush: javafx; title: ; notranslate">
import javafx.scene.control.*;

ListView {
    items: [1.23, -3.33, -4.83, 5.32, -6.32]
    cellFactory: function() {
        def cell:ListCell = ListCell {
            styleClass: bind if ((cell.item as Number) &lt; 0) then &quot;negative&quot; else &quot;list-cell&quot;
            node: Label { text: bind if (cell.empty) then &quot;&quot; else &quot;{cell.item}&quot; }
        }
    }
}
</pre>
<p>You would then update the CSS file so that the text-fill of anything with a styleClass equal to &#8220;negative&#8221; would use red:</p>
<pre class="brush: css; title: ; notranslate">
.negative {
    -fx-text-fill: red
}
</pre>
<p>There is one problem with this solution in JavaFX 1.3 however, which is that we currently only support a single style class, whereas in HTML CSS multiple style classes are supported. We&#8217;re working hard on fixing this limitation. In the meantime, you will need to copy a chunk of the default caspian stylesheet for your &#8220;negative&#8221; class for this to work properly:</p>
<pre class="brush: css; title: ; notranslate">
.negative {
    -fx-text-fill: red;
    -fx-cell-size: 24;
    -fx-padding: 3;
    -fx-background-color: -fx-control-inner-background;
}

.negative:focused {
    -fx-background-insets: 0, 1.4;
    -fx-background-color: -fx-focus-color, -fx-control-inner-background;
}

.negative:odd {
    -fx-background-color: derive(-fx-control-inner-background,-5%);
}

.negative:focused:odd {
    -fx-background-insets: 0, 1.4;
    -fx-background-color: -fx-focus-color, derive(-fx-control-inner-background,-5%);
}

.negative:filled:selected:focused, .negative:filled:selected {
    -fx-background: -fx-accent;
    -fx-background-color: -fx-selection-bar;
    -fx-text-fill: -fx-selection-bar-text;

}
</pre>
<p><strong>Cell Factories</strong><br />
Although the code necessary for creating cell factories is relatively terse, it is also repetitive boilerplate that could be (and should be) handled by libraries. For example, you could provide static functions which create various standard ListCell factories:</p>
<pre class="brush: javafx; title: ; notranslate">
import javafx.scene.control.*;

function currencyCellFactory():ListCell {
    def cell:ListCell = ListCell {
        node: Label { text: bind if (cell.empty) then &quot;&quot; else &quot;${%(,.2f cell.item as Number}&quot; }
    }
}

ListView {
    items: [1.23, 5.23, 4.44, 5.93, 1.34, 33.23]
    cellFactory: currencyCellFactory
}
</pre>
<p>Or the following example might be used to generate a cell factory which can format dates according to some specified format String:</p>
<pre class="brush: javafx; title: ; notranslate">
import javafx.scene.control.*;

function dateCellFactory(format:String):ListCell {
    // ... exercise left to the reader
    ListCell { }
}

ListView {
    items: [date1, date2, date3, date4]
    cellFactory: dateCellFactory(&quot;%tF&quot;)
}
</pre>
<p>There are times when you may wish to create much more elaborate factories based on many different parameters. One approach is to create a class which represents the state of the factory, and which has one or more factory functions on it. For example, I might write the following class:</p>
<pre class="brush: javafx; title: ; notranslate">
 public class MyCellFactory {
     public var format:String;
     public function listCellFactory():ListCell {
         ...
     }
     public function treeCellFactory():TreeCell {
         ...
     }
}
</pre>
<p>And then when creating my ListView or TreeView, I could instantiate an instance of MyCellFactory and then link to the appropriate cellFactory function defined on that class:</p>
<pre class="brush: javafx; title: ; notranslate">
 ListView {
     items: [1.23, 3.24, 5.32]
     cellFactory: MyCellFactory { format: &quot;%(,.2f&quot; }.listCellFactory
 }
</pre>
<p>In this way the parameters, functions, state, and so forth associated with the custom cell factories can be grouped together in a sensible way.</p>
<p><strong>Building a panel of data</strong><br />
Since the content node of a Cell may be any node type, it is possible to build up more complicated Cell content than a single text string. For example, suppose you wanted to produce a ListView that was composed of a Label and a Button. Suppose each of these cells represents a Job object in your application&#8217;s domain model. Perhaps clicking the button is supposed to start a Job. You might build the cell like this:</p>
<pre class="brush: javafx; title: ; notranslate">
ListView {
    items: bind jobs
    cellFactory: function() {
        def cell:ListCell = ListCell {
            node: HBox {
                spacing: 7
                content: [
                    Label { text: bind if (cell.empty) then &quot;&quot; else &quot;{(cell.item as Job).title}&quot; }
                    Button {
                        text: &quot;Start&quot;
                        visible: bind cell.selected and not cell.empty
                        action: function() {
                            def job = cell.item as Job;
                            job.start();
                        }
                    }
                ]
            }
        }
    }
}
</pre>
<p>When the Cell is selected, the <code>visible</code> attribute of the Button changes to true and you can see the button. Click on the button and it will start the Job. You can create arbitrarily complicated Cells in this manner.</p>
<p>These are just a few of the many interesting things that can be done with the ListView control in JavaFX 1.3. We&#8217;ll have additional blog posts in the near future showing in more detail some specific tricks (such as how to make a cell change size dynamically, and some more Jasper-approved visual design tweaks to make ListView really stand out).</p>
<p>In the meantime, here&#8217;s a call to action for all you experts out there doing library work (hint hint, Stephen and Dean). I&#8217;m excited to see what kind of cool libraries of cell factories can be built to make the ListView control really sweet to use!</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2010/04/new-to-javafx-1-3-cells/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Encapsulation Idiom in JavaFX</title>
		<link>http://fxexperience.com/2009/12/encapsulation-idiom-in-javafx/</link>
		<comments>http://fxexperience.com/2009/12/encapsulation-idiom-in-javafx/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 23:45:30 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tips n' Tricks]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=537</guid>
		<description><![CDATA[One of the gratifying things about being involved in building a new platform on top of a new language is discovering new language idioms. As an industry we&#8217;d managed to put together quite a long list of patterns and best practices for Java, but since JavaFX introduces some new concepts (such as object literal notation) [...]]]></description>
			<content:encoded><![CDATA[<p>One of the gratifying things about being involved in building a new platform on top of a new language is discovering new language idioms. As an industry we&#8217;d managed to put together quite a long list of patterns and best practices for Java, but since JavaFX introduces some new concepts (such as object literal notation) and makes other things really easy to do (binding, closures) it creates an environment where we need to discover the best practices and patterns that make for effective programming in JavaFX.</p>
<p>One such idiom has to do with encapsulation. I was presented with the following problem in a recent email. The developer wanted to create a chunk of scenegraph which looked differently depending on some flag. There would be 10 such flags with 10 such chunks of scenegraph. <span id="more-537"></span>In essence here is what the raw code would look like:</p>
<pre class="brush: javafx; title: ; notranslate">
def imgPending = Image { url: &quot;...&quot; }
def imgDone = Image { url: &quot;...&quot; }

var flag1 = false;
var flag2 = false;
var flag3 = false;
// ... and so on

var group = Group {
    content: [
        HBox {
            content: [
                Text { content: &quot;Item 1&quot; }
                ImageView { image: bind if (flag1) then imgPending else imgDone }
            ]
        }
        HBox {
            content: [
                Text { content: &quot;Item 2&quot; }
                ImageView { image: bind if (flag2) then imgPending else imgDone }
            ]
        }
        HBox {
            content: [
                Text { content: &quot;Item 3&quot; }
                ImageView { image: bind if (flag3) then imgPending else imgDone }
            ]
        }
        // ... and so on
    ]
}
</pre>
<p>So for each flag we&#8217;re creating a different HBox with a Label and ImageView. The ImageView shows a different image based on the flag. Clearly the code as written is simple enough but really verbose. It is ripe for copy/paste errors and makes maintenance painful. What can we do about it?</p>
<p>In JavaFX, the best way to encapsulate a chunk of scenegraph such as this is to create a CustomNode. In JavaFX 1.3 you also have the option of extending directly from Parent. For the sake of this article, I&#8217;ll stick with the 1.2 approach (which still works in 1.3) and extend from CustomNode.</p>
<p>Unlike a Group, CustomNode is a Parent node who&#8217;s content is private. This gives you a nice way to encapsulate some chunk of scenegraph and provide a nice clean API to it without having to expose to everybody the actual details of that private chunk of scenegraph. The other benefit to this form of encapsulation is that it helps to clean up your source code by breaking it up into logical chunks.</p>
<p>Here is the reworked example using proper encapsulation:</p>
<pre class="brush: javafx; title: ; notranslate">
// in Indicator.fx
def imgPending = Image { url: &quot;...&quot; }
def imgDone = Image { url: &quot;...&quot; }

public class Indicator extends CustomNode {
    public var text:String;
    public var done:Boolean;

    override function create() {
        HBox {
            content: [
                Label { content: bind text }
                ImageView { image: bind if(not done) then imgPending else imgDone }
            ]
        }
    }
}
</pre>
<pre class="brush: javafx; title: ; notranslate">
// in Main.fx
var flag1 = false;
var flag2 = false;
var flag3 = false;
// ... and so on

var group = Group {
    content: [
        Indicator { text: &quot;Item 1&quot;, done: bind flag1 }
        Indicator { text: &quot;Item 2&quot;, done: bind flag2 }
        Indicator { text: &quot;Item 3&quot;, done: bind flag3 }
        // ... and so on
    ]
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/12/encapsulation-idiom-in-javafx/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>That Infernal Scenegraph Warning Message: Part Deux</title>
		<link>http://fxexperience.com/2009/12/that-infernal-scenegraph-warning-message-part-deux/</link>
		<comments>http://fxexperience.com/2009/12/that-infernal-scenegraph-warning-message-part-deux/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 17:25:01 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Links]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=295</guid>
		<description><![CDATA[Stuart Marks has written up part II of the three-part series on the scenegraph warning message that you have seen in JavaFX1.2. I covered and linked to the first version previously. It really is a terrific read, and details some of the subtle semantics of bind. Stuart always does such an excellent job describing these [...]]]></description>
			<content:encoded><![CDATA[<p>Stuart Marks has <a href="http://stuartmarks.wordpress.com/2009/12/04/that-infernal-scene-graph-warning-message-ii/">written up part II</a> of the three-part series on the scenegraph warning message that you have seen in JavaFX1.2. I <a href="http://fxexperience.com/2009/10/that-infernal-scene-graph-warning-message/">covered and linked to the first version previously.</a> It really is a terrific read, and details some of the subtle semantics of <b>bind</b>. Stuart always does such an excellent job describing these subtle issues.</p>
<blockquote><p>
In my earlier post on this topic I hinted that we had found a resolution to the issue surrounding the warning message, I hinted further in some of my replies to comments, and I even left it as sort of a cliffhanger as to what the resolution was. So, here’s the resolution.</p>
<p>We’ve decided that when a node is added to a group, that node is automatically removed from the group that previously owned it, if any. (Let’s call this the “auto-remove” feature.) We’ve also decided to turn off the warning message by default, but to have it be enabled optionally, possibly via a system property, for debugging purposes. Finally, we’ve relaxed the enforcement of some scene graph invariants in cases where the group’s content sequence is bound.</p>
<p>&#8230;</p>
<p>During the development of our current release, we kept running into this issue. A couple of us wrote code that we thought was reasonable, yet it surprised us when the warning message came out! We had a few hallway conversations from time to time, but a clear-cut answer never emerged. Finally, we realized that we had to get the interested parties in a room and have a knock-down, drag-out meeting to resolve the issue. And so on October 7, 2009, Amy Fowler, Kevin Rushforth, Richard Bair, and I got into a conference room to decide the issue. Three hours later — with no breaks! — we had decided. Actually, it was a great meeting, without a lot of conflict. There were just a lot of issues to cover. Each of us came into the meeting with our initial opinions, but the issues were so close that I think each one of us switched sides at least once during the meeting.
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/12/that-infernal-scenegraph-warning-message-part-deux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Node Lookup</title>
		<link>http://fxexperience.com/2009/11/node-lookup/</link>
		<comments>http://fxexperience.com/2009/11/node-lookup/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 10:36:02 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=192</guid>
		<description><![CDATA[The Node class has a lookup function which is used for finding a node in the scenegraph based on an id. Every node has a String id, similar to HTML. In theory it should be unique within the scenegraph though in practice this isn&#8217;t necessarily the case. This lookup function currently only operates over the [...]]]></description>
			<content:encoded><![CDATA[<p>The Node class has a lookup function which is used for finding a node in the scenegraph based on an id. Every node has a String id, similar to HTML. In theory it should be unique within the scenegraph though in practice this isn&#8217;t necessarily the case.</p>
<p>This lookup function currently only operates over the &#8220;public&#8221; or &#8220;logical&#8221; scenegraph, not the physical one. For example, a Button is a Control which delegates its visuals to its Skin. The Skin has a sub-scenegraph. But since we typically want to encapsulate all that, we hide it from the programmer such that most things don&#8217;t find this part of the scenegraph. Seems like a reasonable thing to do (Swing went the other way and all the gory details were public which led to issues sometimes where people would dig around and rely on internal details &#8212; the horror! &#8212; and this made it incredibly difficult to fix bugs later in Swing).</p>
<p>CustomNode was our level of encapsulation. Any CustomNode&#8217;s children was explicitly not part of the public API. However, a number of people have complained, likely because they aren&#8217;t using CustomNode for encapsulation but rather for modularization of their source code (ie: break a huge file into several files where each piece extended from CustomNode).</p>
<p>So it seems like this partitioning of &#8220;logical&#8221; and &#8220;physical&#8221; scenegraphs is quite confusing at times. So the question is, should the lookup function operate on the physical scenegraph? Vote!</p>
Note: There is a poll embedded within this post, please visit the site to participate in this post's poll.
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/11/node-lookup/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>That Infernal Scene Graph Warning Message</title>
		<link>http://fxexperience.com/2009/10/that-infernal-scene-graph-warning-message/</link>
		<comments>http://fxexperience.com/2009/10/that-infernal-scene-graph-warning-message/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 15:17:58 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=186</guid>
		<description><![CDATA[Stuart Marks (one of the UI Controls &#8220;heavies&#8221;) has a great write-up on that &#8220;Infernal Scene Graph Warning Message&#8221;. You know, the one that showed up in JavaFX 1.2 in seemingly innocuous situations such as the following: In this code, whenever &#8220;someX&#8221; changes, a new Group is created and the node is mysteriously moved from [...]]]></description>
			<content:encoded><![CDATA[<p>Stuart Marks (one of the UI Controls &#8220;heavies&#8221;) has <a href="http://stuartmarks.wordpress.com/2009/10/12/that-infernal-scene-graph-warning-message/">a great write-up on that &#8220;Infernal Scene Graph Warning Message&#8221;</a>. You know, the one that showed up in JavaFX 1.2 in seemingly innocuous situations such as the following:</p>
<pre class="brush: javafx; title: ; notranslate">
var g = bind Group {
    translateX: someX
    content: node
}
</pre>
<p>In this code, whenever &#8220;someX&#8221; changes, a new Group is created and the node is mysteriously moved from this Group to the new one, and in the process the &#8220;infernal scenegraph warning message&#8221; is printed. Stuart goes into a lot of great history and detail to give context to the problem, but here is probably the money-quote as to why the warning message was useful:</p>
<blockquote><p>
When we added the enforcement code, we were surprised that it uncovered a few bugs and quite a number of questionable coding practices in our code, both in our runtime library and in our samples. In one case a node from the scene graph was also being used as a clip. This was illegal and didn’t actually work, but nobody had noticed up to that point. As for questionable coding practices, the enforcement turned up quite a number of cases where a scene graph was being constructed with some initial structure, and some code later on would rearrange the nodes into a different structure for no good reason. This caused the scene graph machinery to do a lot of extra work. The fix was to rewrite the code to create the scene graph in the desired structure, avoiding the rearranging and any error messages that the old code had caused.
</p></blockquote>
<p>Go visit his blog to get more information, I&#8217;m waiting for the second installment which I anticipate will go into all the nitty gritty details. Its kind of a cliff hanger because he doesn&#8217;t tell you what the final <b>unanimous</b> decision was regarding the warning message. Codify it as an error? Remove it? Something else?</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/10/that-infernal-scene-graph-warning-message/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>UI Virtualization</title>
		<link>http://fxexperience.com/2009/09/ui-virtualization/</link>
		<comments>http://fxexperience.com/2009/09/ui-virtualization/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 16:10:12 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Controls]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=167</guid>
		<description><![CDATA[A detailed look at how custom cells and UI Virtualization is going to be handled in ]]></description>
			<content:encoded><![CDATA[<p>When you have a lot of data to display in a Control such as a ListView, you need some way of virtualizing the Nodes created and used. For example, if you have 10 million data items, you don&#8217;t want to create 10 million Nodes. So you create enough Nodes to fill the display dynamically. Because of our heritage in Swing, we know how critical this is for real apps. I got an optimization issue reported this morning on &#8220;UI Virtualization&#8221;. <span id="more-167"></span>The report included the following link to a Silverlight blog describing what they&#8217;re doing in Silverlight 3: <br />
<a href="http://bea.stollnitz.com/blog/?p=338">http://bea.stollnitz.com/blog/?p=338</a></p>
<p>
Having spent several weeks on this problem during the Spring and Summer of this year, the blog on how Silverlight is addressing the issue I found very interesting. It&#8217;s fun for me as a developer to see my counterparts in other toolkits wrestling with the same issues and coming to many of the same conclusions. In this case I think we have a stronger solution. I&#8217;m going to do a little compare and contrast not in the spirit of competition but rather just to describe what we&#8217;re doing.</p>
<p>
In the 1.2 release of JavaFX we released the ListView (our equivalent of ListBox in WPF/Silverlight or JList in Swing). The ListView wasn&#8217;t very customizable. Each list item would only display the &#8220;toString&#8221; of the associated data item. However, the guts of the ListView were very complex to support UI Virtualization. Following JavaOne I completely rewrote the Control. The current implementation (still being finalized by some great engineers on the UI Controls team) now exposes API for allowing you to completely customize each cell while also being very efficient in terms of handling very large lists.</p>
<p>
During the refactoring I created a (currently private) class called VirtualizedFlow which handles most of the dirty work. I found reading the Silverlight blog linked to above that WPF has a similar class, called VirtualizingStackPanel. It&#8217;s always fun to see how other people address the same problem, and a lot of fun when you find out you came to the same conclusions.</p>
<blockquote><p>
WPF has supported UI virtualization for a long time. The ListBox and ListView controls use VirtualizingStackPanel as their default panel, and VSP knows to create UI containers (ListBoxItems or ListViewItems) when new items are about to be shown in the UI, and to discard those containers when items are scrolled out of view.
</p></blockquote>
<p>
This is a good start, but actually not good enough. Another feature I built into ListView from the start (1.2 release) was the notion of recycling the cells used. In the Silverlight blog, it is mentioned that .NET 3.5 SP1 also supports this:</p>
<blockquote><p>
.NET 3.5 SP1 supports the reuse of UI containers already in memory. For example, imagine that when a ListBox is loaded, 30 ListBoxItems are created to display the visible data. When the user scrolls the ListBox, instead of discarding ListBoxItems that scroll out of view and creating new ones for the data items that scroll into view, WPF reuses the existing ListBoxItems. This results in significant performance improvements compared to previous versions because it decreases the time spent initializing ListBoxItems. And since garbage collection is not instantaneous, it also reduces the number of ListBoxItems in memory at one time.
</p></blockquote>
<p>However, unlike .NET which requires you to take a separate step to enable recycling, we do it always and for free. The JavaFX API is designed such that it is a natural part of how the system works. When designing the JavaFX API, I wanted to avoid some of the odd corner cases that came out of Swing&#8217;s cell renderer concept, but keep the insane scalability. I think we&#8217;ve managed that. It is a little more complicated than the simple naive approach of creating a new Cell for every item, but not by much.</p>
<p>
The basic concept in JavaFX revolves around the concept of a Cell (which is a Node). Cells are used to display data items in a ListView (and in the future, a TreeView and TableView and TreeTableView, etc). Each Cell represents a data item, though which data item is represented may change over time. For example, suppose I had the following ListView:</p>
<pre class="brush: javafx; title: ; notranslate">
ListView {
    items: [1..1000]
}
</pre>
<p>This ListView will display the numbers 1 through 1000. Initially, enough Cells will be created to display each visible row. So you may have a Cell which will represent data item &#8220;1&#8243;, and another which represents data item &#8220;2&#8243;, and so forth maybe up to &#8220;10&#8243;. If the user then scrolls, then we will attempt to reuse Cells. So the Cell which used to represent &#8220;1&#8243; now represents &#8220;33&#8243;.</p>
<p>
When you look at the Cell API this is apparent:</p>
<pre class="brush: javafx; title: ; notranslate">
public class Cell extends CustomNode, Resizable {
    /**
     * The data value associated with this Cell. This value is set by the
     * multiviewed Control when the Cell is created or updated. This represents
     * the raw data value.
     */
    public var item:Object;

    /**
     * Indicates whether or not this cell has been selected.
     */
    public var selected:Boolean;

    /**
     * Called by the system whenever the state of the Cell has been updated.
     */
    public var onUpdate:function():Void;

    /**
     * A container for the nodes that represent the content of this cell. Since
     * Cells must be resized to fit within some space, and since their preferred
     * sizes are important for determining the size of a cell, a Container of
     * some kind is required as the root of the content for the cell.
     */
    public var node:Node;

    /**
     * The container for the nodes used to represent the background of the cell.
     * If this is left empty, then the Skin for the Control is responsible for
     * creating a default background, if it so chooses. In this way, custom
     * cells can be created that define both the content and background, or that
     * define only the content with the background being provided by the skin.
     */
    public var background:Node;
}
</pre>
<p>As you can see in this API, each Cell has an <code>item</code> and the item can change over time. The Cell also has a <code>node</code> which represents the cell&#8217;s body, as well as a <code>background</code> which is typically used for rendering selection and so forth and if left null will be supplied by the ListView skin implementation. So to create a custom Cell, all you would need to do is provide the node, and wire it up (bind it) to the item. The system then will reuse Cells, simply updating the item over time as the Cell represents something different, and the bindings will then update the node. There is also a procedural approach where we invoke an onUpdate function variable, which allows the Cell author to respond procedurally if it makes more sense (for example, when working with FXD content exported from the JavaFX Production Suite this might make sense).</p>
<p>
The last part of the puzzle is some way for the system to create your custom Cell whenever it needs a new one (which it pools up itself). This is actually very trivially done by exposing a function variable callback on ListView which allows you to create and return a new Cell. In this way you can create custom Cells for representing data richly in your JavaFX apps.</p>
<pre class="brush: javafx; title: ; notranslate">
ListView {
    items: [1..1000]
    cellFactory: function():ListCell {
        ListCell {
            node: Panel { ... }
        }
    }
}
</pre>
<p>Since cell factories are simple functions, it is also easy to create shared libraries of static functions which return your own implementations and reuse them across your application. You can also subclass ListCell with your own custom implementations so as to reuse them across your application.</p>
<p>
There is one last thing that JavaFX does that I think is quite unique (from the blog it doesn&#8217;t look like Silverlight supports it, and I don&#8217;t think Flex does, however Android might I&#8217;m not sure). First I&#8217;ll quote from the Silverlight blog as to the problem:</p>
<blockquote><p>
Currently WPF supports UI virtualization only when scrolling by item. Pixel-based scrolling is also called “physical scrolling” and item-based scrolling is also called “logical scrolling”.<br />
[...]<br />
I’m often asked if there is a way to work around this limitation. Well, anything is possible, but there is no *easy* workaround. You would have to re-implement significant portions of the current virtualization logic to combine pixel-based scrolling with UI virtualization. You would also have to solve some interesting problems that come with it. For example, how do you calculate the size of the thumb when the item containers have different heights? (Remember that you don’t know the height of the virtualized containers – you only know the height of the containers that are currently displayed.) You could assume an average based on the heights you do know, or you could keep a list with the item heights as items are brought into memory (which would increase accuracy of the thumb size as the user interacts with the control). You could also decide that pixel-based scrolling only works with items that are of the same height – this would simplify the solution. So, yes, you could come up with a solution to work around this limitation, but it’s not trivial.
</p></blockquote>
<p>We have the exact same problem space &#8212; we support non-homogenous row heights, potentially incredibly large numbers of items, and scrolling. This presents some really interesting problems. We have a solution to this problem which for typical ListView&#8217;s combines pixel scrolling with position (or item) scrolling in a way that the user cannot detect that we&#8217;re doing anything special behind the scenes. You can &#8220;pan&#8221; the list by using the mouse and it looks like pixel scrolling, or move by items using the keyboard and it looks like item scrolling or drag the scrollbar and you won&#8217;t know if you are pixel scrolling or item scrolling (except in some very, very edge cases) or you can click the &#8220;up&#8221; and &#8220;down&#8221; arrows on the scrollbar and get pixel scrolling. We&#8217;re still working on the thumb size problem which I think will turn out to be some heuristic that adjusts the thumb size as it finds out more information on the size of the list (typically for large lists you can assume it needs to be the min size, while on small lists you might just create enough cells to get a reasonably accurate thumb. It only goes awry if you have whacked out differences in cell heights).</p>
<p>
So since I want to close out the optimization issue report, I decided to write this blog detailing what we&#8217;re planning on doing. Each of our multi-valued controls (list, tree, table, etc) will use the same base Cell API (unlike TreeCellRenderer, TableCellRenderer, ListCellRenderer which were all different in some annoying ways). They&#8217;ll all support UI virtualization. Initially we won&#8217;t support &#8220;model virtualization&#8221; (ala TableModel, ListModel, TreeModel) though that will be coming in a future release.</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/09/ui-virtualization/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Controls: autoSize</title>
		<link>http://fxexperience.com/2009/07/controls-autosize/</link>
		<comments>http://fxexperience.com/2009/07/controls-autosize/#comments</comments>
		<pubDate>Sat, 11 Jul 2009 21:21:51 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Controls]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=119</guid>
		<description><![CDATA[One bug which gets filed over and over again is related to the idea of whether Controls should resize themselves when their content / settings change. The earliest such bug was with TextBox. TextBox has a columns property which, like in Swing, can be used to hint how many &#8220;columns&#8221; of text should be displayable [...]]]></description>
			<content:encoded><![CDATA[<p>One bug which gets filed over and over again is related to the idea of whether Controls should resize themselves when their content / settings change. The earliest such bug was with TextBox. TextBox has a <code>columns</code> property which, like in Swing, can be used to hint how many &#8220;columns&#8221; of text should be displayable in the Control by default. The TextBox skin implementation uses this information in conjunction with the font and other settings to determine the preferred width of the TextBox.</p>
<p>When a Control is created, if you do not explicitly specify its width or height, then it is sized according to its preferred width and/or preferred height. If you use a Control within a layout Container (which was anticipated as being the common case) then you (almost) never explicitly manage its dimensions – you leave that chore to the Container. However, if you do not use a Control within a layout Container (which turns out seems to happen quite a bit) then it does not explicitly resize itself whenever, say, <code>columns</code> changes.</p>
<p>Take Button as another example. If you create a Button with the text &#8220;OK&#8221; and do not specify a width or height, then the Button will be initialized to its preferred size. However, if you then change the text of the Button to be &#8220;Cancel&#8221;, then the Button will not automatically resize, and will therefore not be wide enough to display all the text and you&#8217;ll see something like &#8220;C&#8230;&#8221;, if you&#8217;re lucky. Or &#8220;&#8230;&#8221; if you&#8217;re not.</p>
<p>I&#8217;ve filed RFE http://javafx-jira.kenai.com/browse/<a href="http://javafx-jira.kenai.com/browse/RT-5122">RT-5122</a> targeted at the next release. The idea here is to have an &#8220;autoSize&#8221; variable on Control which will be true by default. Problem solved, right? Well, not quite. The problem with <code>autoSize</code> is that when placed in a Container, the Control should not attempt to resize itself. So we&#8217;ll end up with code essentially like this:</p>
<pre class="brush: javafx; title: ; notranslate">
if (autoSize and not (parent instanceof Container)) {
    // resize the width because the text has changed, or whatnot
}
</pre>
<p>Not very pretty. But given the options and the amount of frustration it is causing developers, I&#8217;m willing to accept that bit of nastiness. What do you think? Have any good ideas? Leave comments &#038; votes on the bug if you like!</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/07/controls-autosize/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Background Tasks in JavaFX</title>
		<link>http://fxexperience.com/2009/06/background-tasks-in-javafx/</link>
		<comments>http://fxexperience.com/2009/06/background-tasks-in-javafx/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 15:01:32 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=116</guid>
		<description><![CDATA[While on vacation I&#8217;ve been watching twitter to see what kinds of things people are doing with JavaFX. One thing I&#8217;ve seen a fair amount of tweets on that is pretty gratifying is tying JavaFX to backend data services. One project is a port of Cairngorm from Flex to Java/JavaFX. Another was an earlier demo [...]]]></description>
			<content:encoded><![CDATA[<p>While on vacation I&#8217;ve been watching twitter to see what kinds of things people are doing with JavaFX. One thing I&#8217;ve seen a fair amount of tweets on that is pretty gratifying is tying JavaFX to backend data services. One project is a port of <a href="http://code.google.com/p/cairngorm-fx">Cairngorm from Flex to Java/JavaFX</a>. Another was an <a href="http://hessian.caucho.com/ria/">earlier demo based on Hessian</a> (which needs to be ported to JavaFX 1.2). Another was about integrating <a href="http://exadel.com/web/portal/flamingo">Flamingo</a> to JavaFX.</p>
<p><span id="more-116"></span>It&#8217;s great to see a lot of people starting to play with this part of the JavaFX space because we haven&#8217;t really given much guidance to it yet. We do have some great web service APIs as a starting point (basic HTTP with HttpRequest, RSS and ATOM feed support), but haven&#8217;t so far given any guidance as to writing an end to end app. I wanted to take just a moment and outline how we designed the Task API and how it ought to be used by third parties when creating background tasks or services, including communicating with a server.</p>
<p>I also wanted to give a shout out to <a href="http://blogs.sun.com/baechul/">an excellent blog by my colleague Baechul</a> who has been writing some very detailed and well written articles on JavaFX. Of particular interest to this post is one he wrote on <a href="http://blogs.sun.com/baechul/entry/javafx_1_2_async">JavaFX 1.2 Async</a>.</p>
<p>The Task class in the javafx.async represents the basic programming model for all asynchronous tasks in JavaFX and should form the base class for all such background Tasks. Its design was heavily influenced by the excellent work of Hans Muller on the Swing Application Framework. All JavaFX Tasks have the notion of &#8220;state&#8221; and &#8220;progress&#8221;. The state of the Task is expressed though a series of public API members:</p>
<ul>
<li>started:Boolean</li>
<li>stopped:Boolean</li>
<li>failed:Boolean</li>
<li>succeeded:Boolean</li>
<li>done:Boolean</li>
</ul>
<p>We chose to break these states out into Boolean properties rather than have a single property with an enum for two reasons. First, it makes it a little cleaner in the onDone event handler to find out what state the Task ended up in, especially when checking for several states. Second, this allows you to bind to the state of the Task from an external class using some rather clean code. For example, suppose you had a progress indicator and error icon and wanted to make it so that if the task failed, the error icon would be made visible, otherwise the progress indicator would be visible and display progress appropriately.</p>
<pre class="brush: javafx; title: ; notranslate">
Group {
    content: [
        ProgressIndicator {
            visible: bind task.started and not task.failed and not task.stopped
            progress: bind task.percentDone
        }
        ErrorIndicator { // this class doesn't exist, but you could write a CustomNode
            visible: bind task.started and task.failed
            causeOfFailure: bind task.causeOfFailure
        }
    ]
}
</pre>
<p>You&#8217;ll notice in this code block I&#8217;m also taking advantage of another really nice feature of Task and ProgressIndicator. A ProgressIndicator has a <code>progress</code> property which, if -1, means it is indeterminate but if between 0 and 1 then it indicates the percent done. Task also has a similar property called <code>percentDone</code> where, if -1, it means that the progress of the Task is also indeterminate. This makes binding a ProgressIndicator to a Task very clean. Simply bind like this: <code>ProgressIndicator { progress: bind task.percentDone }</code> and the rest works exactly like it should (switching between determinate and indeterminate mode automatically).</p>
<p>There are several API members for tasks for tracking progress:</p>
<ul>
<li>progress</li>
<li>maxProgress</li>
<li>percentDone</li>
</ul>
<p>To help explain these properties lets imagine that our Task was to read a file from disk. In this case, <code>progress</code> could be used to indicate the number of bytes read from disk. <code>maxProgress</code> would indicate the size of the file in bytes, and <code>percentDone</code> would be automatically calculated based on <code>progress</code> and <code>maxProgress</code>. In this way, you can create a UI which will track not only the percent done, but also the discrete amount of work to be done, and how much has been done.</p>
<p>Another simple example would be computing prime numbers. Suppose your app wanted to compute the first 5 prime numbers. In this case, <code>maxProgress</code> would be 5, and <code>progress</code> would be incremented each time a prime number is computed.</p>
<p>Finally, there are two event handlers that all Tasks share: <code>onStart</code> and <code>onDone</code>. <code>onStart</code> is called whenever the Task&#8217;s <code>start()</code> method is called, <em>not</em> when the background task is actually started. For example, your Task implementation might push work onto a worker queue. In this case, <code>onStart</code> should be called immediately after <code>start()</code> is invoked, not when the actual background worker that was pushed on the queue starts working.</p>
<p>The <code>onDone</code> function is called whenever the task stops, for any reason. If the task was cancelled manually, or if there was a failure, or if the task completed successfully. In all these cases onDone will be called. I&#8217;d like to add &#8220;onSuccess&#8221; and &#8220;onFailure&#8221; and &#8220;onStopped&#8221; events in the future. It is the developer&#8217;s responsibility in onDone to check the state of the Task to determine whether the task succeeded or failed or was stopped by checking the state booleans of the Task.</p>
<p>All background operations in JavaFX should extend from Task. This design gives application developers a single common programming model to use with all background operations developed by the JavaFX team or by third party developers. HttpRequest was refactored to be a Task in 1.2 (hence the reason for some of the API changes between 1.1 and 1.2).</p>
<p>There is one major caveat that I need to make clear. As of JavaFX 1.2, JavaFX Script is <strong>single threaded</strong>. <em>All</em> background work <strong>must</strong> be done in Java code. The <code>JavaTaskBase</code> abstract class is the base class intended to be used by all background threading implementations in JavaFX 1.2. Unfortunately, the hookup between <code>JavaTaskBase</code> and <code>RunnableFuture</code> didn&#8217;t come out right in 1.2 and you&#8217;re left with very little guidance as to how to do this appropriately.</p>
<p>The key thing is to understand that <strong>nothing should touch JavaFX variables from a background thread</strong>. So the idiom to use is to have the JavaTaskBase subclass to have a Java language peer which does the background work. The JavaTaskBase subclass would register a listener on the peer, and the peer would communicate back to the JavaTaskBase through that listener interface. The JavaTaskBase subclass would then pump events from the peer back onto the JavaFX thread (i.e. event thread) using FX.deferAction.</p>
<p>That&#8217;s a whole other blog entry though. For starters, I suggest reading <a href="http://blogs.sun.com/baechul/entry/javafx_1_2_async">Baechul&#8217;s take on it</a>.</p>
<p>There is one last thing I wanted to mention, which is a futures item which Brian Goetz and I have been bouncing around a bit. It&#8217;s completely pie-in-the-sky at this point, take it with a grain of salt, etc etc. Having to write background tasks in Java is a pain at the moment primarily because you cannot create JavaFX objects in a background thread. Also, it involves writing a messaging interface, a Java class, and a JavaTaskBase subclass. What I&#8217;d like to see is something like this:</p>
<pre class="brush: javafx; title: ; notranslate">
var task = BackgroundTask {
    run: function() {
        // code in this function runs in a background thread
        defer(function() {
            // code in this function runs on the JavaFX thread
        });
    }
}
</pre>
<p>The kicker is, the compiler would check and enforce that you don&#8217;t illegally modify application state from the background thread, but that you can when using &#8220;defer&#8221; or &#8220;deferAction&#8221;. The thing that gets me all excited about the idea is that we don&#8217;t have to expose a full threading model (with synchronicity, concurrent collections, memory barriers, semaphores, or anything else), but can instead simplify the problem by having a much more limited coarse grained approach of &#8220;this body of work happens in some background thread&#8221;. If you want or need to have a full threading model, then we still make that available by writing a JavaTaskBase subclass, but for the vast majority of uses, you could just use the simplified BackgroundTask model.</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/06/background-tasks-in-javafx/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Skinning Architecture in JavaFX</title>
		<link>http://fxexperience.com/2009/06/skinning-architecture-in-javafx/</link>
		<comments>http://fxexperience.com/2009/06/skinning-architecture-in-javafx/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 20:11:08 +0000</pubDate>
		<dc:creator>Richard Bair</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Controls]]></category>

		<guid isPermaLink="false">http://fxexperience.com/?p=104</guid>
		<description><![CDATA[While Jasper is on vacation I thought I&#8217;d take a moment and outline the multi-level architectural approach we&#8217;ve taken with skinning Controls, and give some rough outline as to when the different levels will be fully supported in JavaFX. There are basically three different levels of support for skinning in JavaFX. At the most basic [...]]]></description>
			<content:encoded><![CDATA[<p>While Jasper is on vacation I thought I&#8217;d take a moment and outline the multi-level architectural approach we&#8217;ve taken with skinning Controls, and give some rough outline as to when the different levels will be fully supported in JavaFX.</p>
<p>There are basically three different levels of support for skinning in JavaFX.</p>
<div id="attachment_105" class="wp-caption aligncenter" style="width: 340px"><a href="http://fxexperience.com/wp-content/uploads/2009/06/skinlevels.png"><img class="size-full wp-image-105" title="skinlevels" src="http://fxexperience.com/wp-content/uploads/2009/06/skinlevels.png" alt="Levels of Skinning" width="330" height="152" /></a><p class="wp-caption-text">Levels of Skinning</p></div>
<p><span id="more-104"></span>At the most basic level, which is also the most powerful and flexible, you have the ability to completely replace the Skin for any Control. The Skin is responsible for the entire visual appearance and, ultimately, the visual interaction for a Control. There are not explicit &#8220;ButtonSkin&#8221; or &#8220;RadioButtonSkin&#8221; or &#8220;ListViewSkin&#8221; types that must be extended. There are simply Skins. So for example, you could completely replace the Skin for a Button using your own implementation that, for instance, simply used an image for the button.</p>
<p>While it is the most powerful mechanism for skinning a Control, it is also the most tedious as there are many details to pay attention to, such as overriding the functions to provide meaningful preferred size information for the Control with this Skin, wiring everything up to the model information in the Control, and handling all the mouse input and preferably forwarding the input on to a Behavior (which you also must providing in JavaFX 1.2 since the skin and behavior implementations for our default look, Caspian, have not been made public in this release).</p>
<p>The next level up restricts a bit what you can do, but also makes it a lot easier to style. This is to use the JavaFX Production Suite to produce skins for your Controls. As of the time of this writing, this support is still in prototype form (Martin Brehovsky demo&#8217;d this at JavaOne and it is definitely something I&#8217;d like to see released this year, but we&#8217;ll see how the schedules work out). The basic idea is pretty simple: the tool would provide its own basic Skin base classes. Vector or Image artwork produced by Illustrator or Photoshop and exported via the Production Suite could then get wired up on top of these Skin base classes to form a complete Skin for a Control.</p>
<p>There are several great things about this approach. First, visual designers can create nice graphics and use these directly. We lowly developer types don&#8217;t have to worry about taking a designer&#8217;s design and replicating it in code (which is good, &#8217;cause mostly we&#8217;re lousy at it). Also, it opens up the opportunity to allow your company to contract out to designers and have them produce skins. It also allows designers to create suites of prebuilt custom skins fairly easily and sell these &#8220;themes&#8221; for the basic controls. Creating custom skins for custom controls is likewise also not terribly difficult for a designer.</p>
<p>However, as mentioned above, this isn&#8217;t released yet, so for the moment you would have to manually wire up the output of an FXD file to the skins. This is actually not very difficult, and could be achieved in a matter of an hour or so by somebody skilled at writing skins.</p>
<p>The third approach is to use CSS for styling the Controls. This is by far the most accessible method and, hopefully, will accommodate the 60-80% use case of simply wanting to style the prebuilt skins. In the 1.2 release, styling Controls with CSS is only just supported. In the next release we&#8217;ll both document and declare &#8220;stable&#8221; the attributes which can be styled from CSS. We&#8217;re pretty excited about the range of options we&#8217;re going to support, because our hope is that we&#8217;ll be able to address the vast majority of uses with just simple CSS.</p>
<p>And remember in JavaFX, CSS attributes can be specified in stylesheets, or directly on Nodes in the scenegraph by specifying the &#8220;style&#8221; property, much like in HTML. This makes it really easy to style a specific Control (which is a Node in the scenegraph) directly, or indirectly in a stylesheet.</p>
<p>In CSS you can easily specify attributes for a Control when it is in different states. For example, you can specify the a Button should have a base color of &#8220;red&#8221;, and a Button which has the mouse over it (hover) is &#8220;blue&#8221;. This is done by specifying the base and/or accent Color in CSS like this:</p>
<pre class="brush: css; title: ; notranslate">
Button {
    style: &quot;base: red&quot;
    text: &quot;Red Button&quot;
}
</pre>
<p>There are a whole host of additional attributes which we&#8217;d like to expose in the next release, such as cornerRadius, padding, margins, shadowFill, textFill, and so forth (actually, I think we have committed to textFill already, I&#8217;ll let Jasper verify). One idea we&#8217;ve been kicking around is that of having a TexturePaint where, from CSS, you could specify an image file and also a set of insets and then we&#8217;d do the 9-square resizing technique for you. This would make it trivial then to build skins from CSS based on either Colors, Gradients, or Images. If we then expose some information for animations so you could control simple animation transitions from CSS too, then CSS becomes a very compelling proposition.</p>
<p>I hope this outline helps understand a bit better where we are now, and where we&#8217;re headed in the next release. Today, the best supported option is to create completely custom Skins. The second best option is to do some basic styling from CSS. In a few months time we plan to release complete CSS customizability which will give probably 80% use case coverage. We should also have basic support in the Production Suite to produce skins for Controls (though there may be some hand coding involved, we&#8217;ll try to make it pretty trivial).</p>
]]></content:encoded>
			<wfw:commentRss>http://fxexperience.com/2009/06/skinning-architecture-in-javafx/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

