<?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>Bits, Bytes &#38; Words</title>
	<atom:link href="http://www.asgteach.com/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.asgteach.com/blog</link>
	<description>Just a simple matter of programming</description>
	<lastBuildDate>Sat, 19 Nov 2011 04:56:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>JavaFX: Properties on Steroids</title>
		<link>http://www.asgteach.com/blog/?p=408&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javafx-properties-on-steroids</link>
		<comments>http://www.asgteach.com/blog/?p=408#comments</comments>
		<pubDate>Sat, 19 Nov 2011 04:56:54 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[JavaFX binding]]></category>
		<category><![CDATA[JavaFX property]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=408</guid>
		<description><![CDATA[At the heart of JavaFX is its scenegraph, a structure that includes (perhaps many) nodes. The JavaFX rendering engine displays these nodes and ultimately what you see depends on the properties of these nodes. Properties are oh-so-important. They make a &#8230; <a href="http://www.asgteach.com/blog/?p=408">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At the heart of JavaFX is its scenegraph, a structure that includes (perhaps many) nodes. The JavaFX rendering engine displays these nodes and ultimately what you see depends on the properties of these nodes.</p>
<p>Properties are oh-so-important. They make a Circle red or a Rectangle 50 pixels wide. They determine the gradient for a background color or whether or not some text includes reflection or a drop shadow effect. You manipulate nodes with layout components—which are themselves nodes—by setting properties such as spacing or alignment. When your application includes animation, JavaFX updates a node’s properties over time—perhaps a node’s position, its rotation, or its opacity.</p>
<p>Before we look at JavaFX properties in detail, let’s review JavaBean properties first. JavaBean properties support encapsulation and a well-defined naming convention. You can create read-write properties, read-only properties, and immutable properties.</p>
<p>For example, here is a simple Person JavaBean with property <code>fullname</code>. (In fact, once we write the instance variable <code>fullname</code>, an IDE can generate the getter and setter.) Because we provide both getter and setter for this String property, the property is read-write. A Person object is built with a default constructor.</p>
<pre class="brush: java; title: ;">
public class Person {
    private String fullname = &quot;&quot;;

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    @Override
    public String toString() {
        return getFullname();
    }
}
</pre>
<p>We can use Person as follows.</p>
<pre class="brush: java; gutter: false; title: ;">
    Person p = new Person();
    p.setFullname(&quot;Joe Smith&quot;);
    System.out.println(p);      // Joe Smith
</pre>
<p>Okay, so what are JavaFX properties and how are they different from regular JavaBean properties? JavaFX properties are JavaBean properties on steroids. That is, like JavaBean properties, they support encapsulation, a well-defined naming convention, as well as read-only, read-write, and immutable attributes. But there’s more. To see the difference, let’s create a Person POJO with a JavaFX property.</p>
<pre class="brush: java; title: ;">
public class Person {
    private StringProperty fullname =
        new SimpleStringProperty(this, &quot;fullname&quot;, &quot;&quot;);

    public final StringProperty fullnameProperty() {
        return fullname;
    }

    public final String getFullname() {
        return fullname.get();
    }

    public final void setFullname(String fullname) {
        this.fullname.set(fullname);
    }

    @Override
    public String toString() {
        return getFullname();
    }
}
</pre>
<p>You’ll notice right away that JavaFX properties include additional implementation code. First, the instance variable type is no longer String, but StringProperty, a type that wraps a String value and provides enhanced JavaFX property behaviors and structure, as you will soon see.</p>
<p>Second, conforming to the JavaFX property naming convention, you access a JavaFX property exactly the same as a JavaBean property. This means client code doesn’t change.</p>
<pre class="brush: java; gutter: false; title: ;">
    // unchanged from JavaBean property
    Person p = new Person();
    p.setFullname(&quot;Joe Smith&quot;);
    System.out.println(p);            // Joe Smith
</pre>
<p>Third, also confirming to the JavaFX property naming convention, you provide access to the Property itself with method <code><em>propertyname</em>Property()</code>. Here is method <code>fullnameProperty()</code> again.</p>
<pre class="brush: java; gutter: false; title: ;">
    public final StringProperty fullnameProperty() {
        return fullname;
    }
</pre>
<p>Fourth, JavaFX properties store contextual information. Method <code>getBean()</code> returns a reference to the enclosing object and <code>getName()</code> returns the property’s name. Here, we initialize these values in the property’s constructor, along with an empty String to use as its initial value.</p>
<pre class="brush: java; gutter: false; title: ;">
    private StringProperty fullname =
            new SimpleStringProperty(this, &quot;fullname&quot;, &quot;&quot;);
</pre>
<p>And, we can use these methods as follows.</p>
<pre class="brush: java; gutter: false; title: ;">
    System.out.println(p.fullnameProperty().getBean());
    // returns p and prints 'Joe Smith'
    System.out.println(p.fullnameProperty().getName());
    // prints 'fullname'
</pre>
<p>As alluded to earlier, JavaFX properties support additional behaviors. JavaFX properties are observable, which means you can attach listeners and define event handlers when a property value changes or becomes invalid. JavaFX properties also support unidirectional and bidirectional binding and unbinding. Binding lets properties participate in dependencies with other property values. Unbinding removes any dependencies. These are powerful constructs that let JavaFX developers write code that easily synchronizes itself based on changing values. These behaviors are important for responsive UIs as well as animation.</p>
<p>Because all JavaFX nodes contain many JavaFX properties, the JavaFX API does not implement properties in the straightforward way I have described. Instead, JavaFX nodes use <em>lazy evaluation</em> for properties. Thus, for any given property, if a node object only gets and sets values, the overhead for that property is equivalent to a regular JavaBean property.</p>
<p>Our Person POJO with its JavaFX property could be re-implemented as follows. Now the actual JavaFX property is created only when the StringProperty object is accessed with <code>fullnameProperty()</code>.</p>
<pre class="brush: java; title: ;">
public class Person {
    private String _fullname = &quot;&quot;;
    private StringProperty fullname;

    public final StringProperty fullnameProperty() {
        if (fullname == null) {
            fullname = new SimpleStringProperty(
                    this, &quot;fullname&quot;, _fullname);
        }
        return fullname;
    }

    public final String getFullname() {
        if (fullname == null) {
            return _fullname;
        }
        else return fullname.get();
    }

    public final void setFullname(String fullname) {
        if (this.fullname == null) {
            _fullname = fullname;
        }
        else this.fullname.set(fullname);
    }

    @Override
    public String toString() {
        return getFullname();
    }
}
</pre>
<p>Note that our user code only inflates <code>fullname</code> (that is, invokes the SimpleStringProperty constructor) after the first call to <code>p.fullnameProperty()</code>, as shown here.</p>
<pre class="brush: java; gutter: false; title: ;">
    Person p = new Person();
    p.setFullname(&quot;Joe Smith&quot;);
    System.out.println(p);

    // JavaFX Property fullname inflated here:
    System.out.println(p.fullnameProperty().getBean());
    // prints 'Joe Smith'
    System.out.println(p.fullnameProperty().getName());
    // prints 'fullname'
</pre>
<p>What about JavaFX properties with types other than String? JavaFX supports the following property types.</p>
<pre class="brush: java; gutter: false; title: ;">
    BooleanProperty, DoubleProperty, FloatProperty,
    IntegerProperty, LongProperty, ObjectProperty&lt;T&gt;, 
    StringProperty
</pre>
<p>These are abstract types and are instantiated with SimpleBooleanProperty, SimpleDoubleProperty, and so forth.</p>
<p>We’ll explore examples with JavaFX properties that use binding next.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=408</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Adding Animation with JavaFX: Spicing Up a Clear</title>
		<link>http://www.asgteach.com/blog/?p=372&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-animation-with-javafx-spicing-up-a-clear</link>
		<comments>http://www.asgteach.com/blog/?p=372#comments</comments>
		<pubDate>Wed, 02 Nov 2011 01:25:15 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[FadeTransition]]></category>
		<category><![CDATA[JavaFX transitions]]></category>
		<category><![CDATA[SequentialTransition]]></category>
		<category><![CDATA[timeline]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=372</guid>
		<description><![CDATA[We return to the same drawing program we described in two previous posts, Sketch Pad: Custom Binding and JavaFX Sketch Pad: Version 2. In this third version, we&#8217;re going to spice up the Clear button by animating a fade. That &#8230; <a href="http://www.asgteach.com/blog/?p=372">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We return to the same drawing program we described in two previous posts, <a href="http://www.asgteach.com/blog/?p=272">Sketch Pad: Custom Binding</a> and <a href="http://www.asgteach.com/blog/?p=327">JavaFX Sketch Pad: Version 2</a>. In this third version, we&#8217;re going to spice up the Clear button by animating a fade. That is, when a user clicks Clear, the drawing elements fade out, one at a time in the reverse order in which they were drawn. So, in the following screenshot with a wonderful hand-drawn greeting (&#8220;Hi JavaFX!&#8221;) on a dark blue background, the exclamation point fades first, then the &#8216;X&#8217;, followed by the &#8216;F&#8217;, and so on. The last to fade are the dark blue background strokes.<br />
<img class="aligncenter size-medium wp-image-200" title="Screenshot of Draw Program with Animation" src="http://www.asgteach.com/blog/wp-content/uploads/drawFade1.jpg" alt="Screenshot of Draw Program with Animation" /></p>
<p>Here is the original Clear button event handler, which simply removes all of the Path nodes in Group <code>lineGroup</code>.</p>
<pre class="brush: java; title: ;">
Button btnClear = new Button();
btnClear.setText(&quot;Clear&quot;);
btnClear.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
    public void handle(ActionEvent event) {
        lineGroup.getChildren().removeAll(
              lineGroup.getChildren());
    }
});
</pre>
<p>In order to construct an animated fade, we&#8217;ll use JavaFX Transitions. Transitions are high-level animation constructs that build timelines, key frames, and key values for you. Transitions are defined to animate key JavaFX node properties. For example, the FadeTransition animates <code>opacity</code>, TranslateTransition animates <code>translateX</code>, <code>translateY</code>, and <code>translateZ</code>, FillTransition animates <code>fill</code>, and ScaleTransition animates the <code>scaleX</code>, <code>scaleY</code>, and <code>scaleZ</code> values.</p>
<p>Furthermore, JavaFX lets you group animations into parallel or sequential transitions. Parallel transitions manage a collection of animations that execute in parallel, while sequential transitions manage animations that execute one after the other. For our application, we&#8217;ll use a FadeTransition to fade the nodes and a sequential transition to fade the Path nodes one at a time.</p>
<pre class="brush: java; title: ;">
// Class variable
private SequentialTransition seqtran = null;
. . .
</pre>
<p>Recall that Group <code>lineGroup</code> holds a collection of Path nodes. Each node contains one or more PathElements that form the drawing element. Let&#8217;s build a FadeTransition for each Path node. A FadeTransition animates a node&#8217;s <code>opacityProperty</code>. To fade <em>out</em> a node (have it disappear), set FadeTransition&#8217;s <code>toValue</code> to 0.0. To fade <em>in</em> a node (make it appear), set <code>toValue</code> to 1.0. If you don&#8217;t provide a value for <code>fromValue</code>, FadeTransition uses the node <code>opacityProperty</code>&#8216;s current value.</p>
<p>So let&#8217;s see how our new Clear button event handler works with Transitions. First, if the drawing canvas is empty, we don&#8217;t do anything and just return. If the sequential transition (<code>seqtran</code>) isn&#8217;t null, then we&#8217;ll stop it. We instantiate a new SequentialTransition and go through the collection of nodes in Group <code>lineGroup</code> to construct a FadeTransition for each node. We specify its duration to be 1,000 milliseconds, set <code>toValue</code> to 0 (making the node fade out), and set <code>interpolator</code> to <code>Interpolator.EASE_BOTH</code>. The default interpolator is <code>LINEAR</code>, providing a constant rate of change for the animation. <code>EASE_IN</code> provides a slower rate of change at the onset of animation, whereas <code>EASE_OUT</code> is a slower rate of change at the end.  <code>EASE_BOTH</code> provides slowing at both ends of the animation.</p>
<p>After configuring the FadeTransition, we add it to the beginning of the SequentialTransition&#8217;s collection of animations, providing the reverse ordering.</p>
<p>When everything is configured, we initiate the sequential animation with method <code>playFromStart()</code>.</p>
<pre class="brush: java; title: ;">
Button btnClear = new Button();
btnClear.setText(&quot;Clear&quot;);
btnClear.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
    public void handle(ActionEvent event) {
        if (lineGroup.getChildren().size() == 0) {
            return;
        }
        if (seqtran != null) {
            seqtran.stop();
        }
        seqtran = new SequentialTransition();
        for (final Node node : lineGroup.getChildren()) {
            FadeTransition ft = new FadeTransition(
                     Duration.millis(1000), node);
            ft.setToValue(0.0);
            ft.setInterpolator(Interpolator.EASE_BOTH);
            // fade in reverse order
            seqtran.getChildren().add(0, ft);
        }

        // Code here to remove the nodes from Group lineGroup
        . . .
        seqtran.playFromStart();
    }
});
</pre>
<p>Ah, but we aren&#8217;t quite finished yet. We don&#8217;t want to just fade out the nodes, we also want to remove them from the scene graph. To do this, we must make sure the fade animation is finished. No problem. First, we&#8217;ll specify a timeline to handle the removal and add this timeline to the <em>end</em> of the sequential transition. We provide an <code>onFinished</code> function for the KeyFrame and put the code that removes the nodes in the <code>onFinished</code> function.</p>
<p>Here is the rest of the Clear button&#8217;s event handler. Note that the KeyFrame&#8217;s duration must not be zero, or the <code>onFinished</code> function does not get invoked. Also, here we specify the <code>onFinished</code> function as part of the KeyFrame constructor (which is why you don&#8217;t see <code>onFinished</code> in the configuration code).</p>
<pre class="brush: java; title: ;">
// Class variable
private Timeline timeline = null;
. . .
// inside btnClear event handler
// Code here to remove the nodes from Group lineGroup
. . .
if (timeline != null) {
    timeline.stop();
}
timeline = new Timeline();
timeline.getKeyFrames().add(
        new KeyFrame(Duration.millis(1),
        new EventHandler&lt;ActionEvent&gt;() {
            public void handle(ActionEvent event) {
                lineGroup.getChildren().removeAll(
                    lineGroup.getChildren());
            }
        }));
seqtran.getChildren().add(timeline);
</pre>
<p>Download the <a href="http://www.asgteach.com/download/blog/JavaFX/Draw3.java">Sketch Pad with Animated Clear JavaFX source code here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=372</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaFX Sketch Pad: Version 2</title>
		<link>http://www.asgteach.com/blog/?p=327&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javafx-sketch-pad-version-2</link>
		<comments>http://www.asgteach.com/blog/?p=327#comments</comments>
		<pubDate>Sun, 30 Oct 2011 23:58:09 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[FlowPane]]></category>
		<category><![CDATA[Java Reflection]]></category>
		<category><![CDATA[JavaFX Color]]></category>
		<category><![CDATA[JavaFX Tooltip]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=327</guid>
		<description><![CDATA[In our previous post we presented a JavaFX Sketch Pad example that uses three RGB sliders to manipulate a drawing line&#8217;s color. In this post, we&#8217;ll use a color picker made with all the JavaFX built-in colors. Since JavaFX colors &#8230; <a href="http://www.asgteach.com/blog/?p=327">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In our <a href="http://www.asgteach.com/blog/?p=272">previous post</a> we presented a JavaFX Sketch Pad example that uses three RGB sliders to manipulate a drawing line&#8217;s color. In this post, we&#8217;ll use a color picker made with all the JavaFX built-in colors. Since JavaFX colors are are static fields with familiar (and maybe not so familiar) names like <code>BLUE</code>, <code>GREEN</code>, and <code>MINTCREAM</code>, we can use them quite easily as follows.</p>
<pre class="brush: java; gutter: false; title: ;">
     Rectangle rec = new Rectangle(5, 5, 60, 30);
     rec.setFill(Color.RED);
</pre>
<p>You can also build a Color object from a color name with Color static method <code>web()</code>.</p>
<pre class="brush: java; gutter: false; title: ;">
     rec.setFill(Color.web(&quot;TURQUOISE&quot;));
</pre>
<p>Here&#8217;s a screenshot of the JavaFX Sketch Pad Version 2.<br />
<a href="http://www.asgteach.com/blog/wp-content/uploads/drawProgram14.jpg"><img src="http://www.asgteach.com/blog/wp-content/uploads/drawProgram14.jpg" alt="JavaFX Sketch Pad Version 2 Screenshot" title="JavaFX Sketch Pad Version 2 Screenshot" class="alignnone size-full wp-image-366" /></a><br />
Note that we&#8217;ve moved the drawing controls below the canvas. The sample line appears at the top. The Clear button and stroke width slider are at the bottom left. At the bottom right, you see 147 color rectangles. Clicking on any of the rectangles changes the drawing color to the selected color (and also changes the color of the sample line).</p>
<p>How should we implement this feature? One way is to create an array of Color objects initialized to each of the static fields in Color.</p>
<pre class="brush: java; gutter: false; title: ;">
    private static final Color[] colors = { Color.ALICEBLUE,
        Color.ANTIQUEWHITE, Color.AQUA,
      . . .
    };
</pre>
<p>Then, we can build a small rectangle for each color and add it to a FlowPane to create a our Color picker.</p>
<p>That works, but too much typing for all the JavaFX colors. Instead, let&#8217;s get all the public static fields in Color and build a Color object with <code>Color.web(color_name)</code> for each rectangle. We can do this with Java reflection. Java stores all kinds of interesting information inside the class object. While reflection is not used that often in application code, it is quite common in development tools (providing code completion choices in Java editors, for example).</p>
<p>Here&#8217;s our color picker code. First, we instantiate a Label to hold the selected color&#8217;s name. We use a FlowPane layout component to hold the color rectangles. FlowPane arranges its children in a flow, filling each successive row, and wrapping (going to the next row) when needed. Properties <code>vgap</code> and <code>hgap</code> provide vertical and horizontal spacing for the rectangles. Property <code>prefWrapLength</code> tells FlowPane when to wrap to the next row. The default behavior is row-wise filling, but column-wise filling is also possible.</p>
<pre class="brush: java; title: ;">
// Use a Label to hold the selected color name
final Label colorLabel = new Label(&quot;color: blue&quot;);
. . .
// Put all the color rectangles in a flow container
FlowPane flow = new FlowPane();

flow.setVgap(2);
flow.setHgap(2);
flow.setPrefWrapLength(400);
</pre>
<p>Next, we&#8217;ll use reflection to grab all of the public static fields for Color. It turns out that the only public static field we want to skip is <code>TRANSPARENT</code>, which creates a see-through color that is not useful with our drawing program. And, just in case the JavaFX development team slips in a public static field that is <em>not</em> a valid Color name, we use a try &#8211; catch block. Color throws an IllegalArgumentException if you attempt to make a Color with an unrecognizable String.</p>
<p>Once we have a Color, we build and configure the rectangle (we&#8217;ll show you the configuration code next), and add the rectangle to the FlowPane layout container.</p>
<pre class="brush: java; title: ;">
// Get the declared fields for the Color class
Field[] colorFields = Color.class.getDeclaredFields();
for (Field fieldname : colorFields) {
    // get the field's modifiers so we can tell
    // if it's public and static
    int mods = fieldname.getModifiers();

    // Only use the field if it's
    // public, static, and NOT 'TRANSPARENT'
    if (Modifier.isPublic(mods) &amp;&amp; Modifier.isStatic(mods)
            &amp;&amp; !(fieldname.getName().equals(&quot;TRANSPARENT&quot;))) {
        try {
            // create a color from the fieldname
            Color c = Color.web(fieldname.getName());
            // Make a rectangle with that field name's color
            final Rectangle r = new Rectangle(15, 15, c);
            // Configure the rectangle
           . . .
            // Add it to the flow container
            flow.getChildren().add(r);
        } catch (IllegalArgumentException e) {
            // just ignore it if for some reason we can't make
            // a color
        }
    }
}
</pre>
<p>To configure each color picker rectangle, we set its cursor to <code>Cursor.HAND</code>. We then build a tooltip. JavaFX provides a built-in Tooltip object that you can easily configure with any JavaFX Control. However, a Rectangle is not a Control (it&#8217;s just a Shape). In this case, use the Tooltip static method <code>install()</code> for the expected pop-up tooltip behavior. We convert the color to lower case because lower case letters are easier to read.</p>
<p>(Note: The standard JavaFX tooltip pops up quite slowly and stays visible for only a short time. There is currently no way to configure the animation properties of a tooltip. I&#8217;m hoping that changes in a future release.)</p>
<p>We also want to display the Color name next to the sample line, since it&#8217;s easier to remember a color&#8217;s name than just viewing it. So, we save the color name (actually, the tooltip&#8217;s text) in the rectangle&#8217;s <code>userData</code> property. Once saved, we can retrieve it when the user selects this color.</p>
<p>The final configuration specifies a mouse clicked event handler for each rectangle. Inside the handler, we set <code>sampleLine</code>&#8216;s stroke property to the rectangle&#8217;s fill property and the <code>colorLabel</code>&#8216;s text property to the text in the rectangle&#8217;s <code>userData</code> (the color name).</p>
<pre class="brush: java; title: ;">
// Configure the rectangle
r.setCursor(Cursor.HAND);
// Create a tooltip
Tooltip t = new Tooltip(fieldname.getName().toLowerCase());
Tooltip.install(r, t);
// Save the color name in userData
r.setUserData(t.getText());

r.setOnMouseClicked(new EventHandler&lt;MouseEvent&gt;() {

    @Override
    public void handle(MouseEvent me) {
        sampleLine.setStroke(r.getFill());
        colorLabel.setText(&quot;color: &quot; +
                ((String) r.getUserData()));
    }
});
</pre>
<p>Have fun sketching! Download the <a href="http://www.asgteach.com/download/blog/JavaFX/Draw2.java">Sketch Pad (Version 2) JavaFX source code here</a>.</p>
<p>We welcome comments and feedback! </p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=327</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaFX Sketch Pad: Custom Binding</title>
		<link>http://www.asgteach.com/blog/?p=272&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javafx-sketch-pad-custom-binding</link>
		<comments>http://www.asgteach.com/blog/?p=272#comments</comments>
		<pubDate>Tue, 25 Oct 2011 00:03:43 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[custom binding]]></category>
		<category><![CDATA[JavaFX binding]]></category>
		<category><![CDATA[JavaFX slider]]></category>
		<category><![CDATA[Path]]></category>
		<category><![CDATA[Path Elements]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=272</guid>
		<description><![CDATA[Sketch pad programs are fun to build and fun to test. And writing a sketch pad program in JavaFX is no different, except that maybe it&#8217;s more fun. So, what constructs do we need to create a decent sketch pad &#8230; <a href="http://www.asgteach.com/blog/?p=272">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sketch pad programs are fun to build and fun to test. And writing a sketch pad program in JavaFX is no different, except that maybe it&#8217;s more fun. So, what constructs do we need to create a decent sketch pad program in JavaFX? At the minimum, we need to</p>
<ul>
<li>Detect mouse events for mouse click, mouse drag, and mouse release</li>
<li>Draw line segments corresponding to where the user clicks and drags the mouse</li>
<li>Clear our sketch pad</li>
</ul>
<p>It would also be nice to</p>
<ul>
<li>Change the width of the line we&#8217;re drawing</li>
<li>Change the color of the line we&#8217;re drawing</li>
</ul>
<p>So, let&#8217;s begin.<div id="attachment_273" class="wp-caption alignleft" style="width: 230px"><img class="size-medium wp-image-273" title="Sketch Pad" src="http://www.asgteach.com/blog/wp-content/uploads/drawProgram6-220x300.jpg" alt="Sketch Pad Program Screenshot" width="220" height="300" /><p class="wp-caption-text">Version 1 JavaFX Sketch Pad Screenshot</p></div></p>
<p>The Version 1 screenshot (including some test scribbles) has a Clear button, three RGB color sliders, a stroke width slider, and a sample line that shows both the current stroke width and color settings. The canvas is a rectangle with a light gray background.</p>
<p>You construct the lines (or scribbles) with the JavaFX Path class, a shape that holds path elements. Path elements include ArcTo, ClosePath, CubicCurveTo, HLineTo, LineTo, MoveTo, QuadCurveTo, and VLineTo. We&#8217;ll only need MoveTo (to position the cursor at the beginning of a drawing action) and LineTo (to draw the line corresponding to the mouse drag). As we build the path, we&#8217;ll add it to a Group called <code>lineGroup</code>.</p>
<p>First, let&#8217;s look at the JavaFX code that builds the <code>lineGroup</code>, sample line (a Line), and <code>canvas</code> (a Rectangle). Note that we set the canvas&#8217; cursor to <code>CROSSHAIR</code> so a user knows when the drawing mouse is active. We set the canvas fill to <code>LIGHTGRAY</code>.</p>
<pre class="brush: java; title: ;">
private Group lineGroup;       //  Class variable
. . .
// A group to hold all the drawn path elements
lineGroup = new Group();
// Build the sample line&lt;
final Line sampleLine = new Line(0, 0, 140, 0);
// Build the canvas
final Rectangle canvas = new Rectangle(scene.getWidth() - 20,
            scene.getHeight() - 200);
canvas.setCursor(Cursor.CROSSHAIR);
canvas.setFill(Color.LIGHTGRAY);
</pre>
<p>Next, we build the path elements in the canvas&#8217; mouse event handlers. Both the stroke width and stroke color are based on the values of the sample line. Let&#8217;s examine the mouse event handlers for mouse pressed, mouse released, and mouse dragged.</p>
<p>The mouse pressed handler defines a new path and makes it transparent to mouse clicks. This lets the user draw new lines on top of previously drawn lines. Since the path is &#8220;in front of&#8221; the rectangle, the path would otherwise consume mouse events. Next, we set the <code>strokeWidth</code> and <code>stroke</code> properties. We add the newly created path to <code>lineGroup</code> and add path element MoveTo as the first element of the path. The x and y coordinates of the MoveTo element are the scene coordinates passed to the mouse event handler.</p>
<pre class="brush: java; title: ;">
private Path path;           // Class variable
. . .
canvas.setOnMousePressed(new EventHandler&lt;MouseEvent&gt;() {
    @Override
    public void handle(MouseEvent me) {
        path = new Path();
        path.setMouseTransparent(true);
        path.setStrokeWidth(sampleLine.getStrokeWidth());
        path.setStroke(sampleLine.getStroke());&lt;
        lineGroup.getChildren().add(path);
        path.getElements().add(
              new MoveTo(me.getSceneX(), me.getSceneY()));
    }
});
</pre>
<p>A mouse dragged event is fired when the user drags the mouse. This can only happen after a mouse pressed event or a previous mouse dragged event. Here we check that the coordinates in the mouse event are within the canvas&#8217; local coordinate space. If the coordinates are indeed within the canvas, we create a LineTo path element and add it to the path. This draws a line on the canvas from the previous mouse pressed or mouse dragged event location. The mouse dragged event handler is invoked multiple times as the user drags the mouse over the canvas.</p>
<pre class="brush: java; title: ;">
canvas.setOnMouseDragged(new EventHandler&lt;MouseEvent&gt;() {
    @Override
    public void handle(MouseEvent me) {
        // keep lines within rectangle
        if (canvas.getBoundsInLocal().contains(
                             me.getX(), me.getY())) {
            path.getElements().add(
                 new LineTo(me.getSceneX(), me.getSceneY()));
        }
    }
});
</pre>
<p>When the user releases the mouse, the system invokes the mouse released event handler. Here, we simply set <code>path</code> to null. Now the user can optionally clear the canvas, change the stroke width, or change the stroke color.</p>
<pre class="brush: java; title: ;">
canvas.setOnMouseReleased(new EventHandler&lt;MouseEvent&gt;() {
    @Override
    public void handle(MouseEvent me) {
        path = null;
    }
});
</pre>
<p>We clear the canvas with the Clear button. This event handler removes all the nodes contained in <code>lineGroup</code>.</p>
<pre class="brush: java; title: ;">
Button btnClear = new Button();
btnClear.setText(&quot;Clear&quot;);
btnClear.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
    public void handle(ActionEvent event) {
        lineGroup.getChildren().
             removeAll(lineGroup.getChildren());
    }
});
</pre>
<p>Recall that a slider controls the stroke width. Let&#8217;s see how this works. First, we define constants to set the slider&#8217;s minimum and maximum values (<code>MINSTROKE</code> and <code>MAXSTROKE</code>). Then, we set the starting stroke width to 3.0, which is a bit larger than the default of 1.0. We use these values to instantiate slider <code>strokeSlider</code>. As the user slides the handle right, the value increases up to the maximum. To track the changes, we <em>bind</em> the <code>sampleLine</code>&#8216;s stroke width property to the value of the slider. This is straightforward, since both properties wrap Double values. As the user moves the slider, the sample line grows and shrinks to reflect its stroke width. Each time the user &#8220;draws&#8221; a line, the canvas&#8217; mouse handler uses the new stroke width value.</p>
<pre class="brush: java; title: ;">
private static final Double DEFAULTSTROKE = 3.0;
private static final Double MAXSTROKE = 30.0;
private static final Double MINSTROKE = 1.0;
. . .
Slider strokeSlider =&lt;br
       new Slider(MINSTROKE, MAXSTROKE, DEFAULTSTROKE);
sampleLine.strokeWidthProperty().bind(
       strokeSlider.valueProperty());
</pre>
<p>Now let&#8217;s configure the line&#8217;s color. To control color, we use a triplet of sliders for the RGB color value. Each value is an integer from 0 to 255. Here are the three sliders and label controls.</p>
<pre class="brush: java; title: ;">
private static final Integer DEFAULTRED = 0;
private static final Integer DEFAULTGREEN = 0;
private static final Integer DEFAULTBLUE = 255;
private static final Integer MAXRGB = 255;
private static final Integer MINRGB = 0;
. . .
// Build the RGB sliders and labels
final Slider redSlider =
        new Slider(MINRGB, MAXRGB, DEFAULTRED);
Label labelRed = new Label(&quot;R&quot;);
final Slider greenSlider =
        new Slider(MINRGB, MAXRGB, DEFAULTGREEN);
Label labelGreen = new Label(&quot;G&quot;);
final Slider blueSlider =
        new Slider(MINRGB, MAXRGB, DEFAULTBLUE);
Label labelBlue = new Label(&quot;B&quot;);
</pre>
<p>Here&#8217;s where things get a bit tricky. To set <code>sampleLine</code>&#8216;s stroke property to a Color based on the combined values of the three RGB sliders, we use static Color method <code>rgb()</code>, as follows (which gets converted automatically to the required Paint object).</p>
<pre class="brush: java; light: true; title: ;">
sampleLine.setStroke(Color.rgb(redSlider.valueProperty().intValue(),
                        greenSlider.valueProperty().intValue(),
                        blueSlider.valueProperty().intValue()));
</pre>
<p>However, just as we provided binding for <code>sampleLine</code>&#8216;s stroke width property to the stroke width slider value, we also need to bind <code>sampleLine</code>&#8216;s stroke property to the Color object made from the combined RGB slider values. When any of the three sliders change, <code>sampleLine</code>&#8216;s stroke property must also change. In this case, there isn&#8217;t a built-in Paint property binding method that computes a new Paint object from an RGB triplet, so we&#8217;ll need to create our own <em>custom</em> binding object.</p>
<p>This ObjectBinding object will be built as an anonymous class. In the constructor we specify the properties that participate in the binding. This builds the necessary listeners that are notified when any of the slider&#8217;s value property changes. Next, we override method <code>computeValue()</code> to specify how a new Paint object is built from the three sliders. Once we build the custom binding object, we can specify the binding for <code>sampleLine</code>.</p>
<pre class="brush: java; title: ;">
// Build a Binding object
// to compute a Paint object from the sliders
ObjectBinding&lt;Paint&gt; colorBinding = new ObjectBinding&lt;Paint&gt;() {
    {
        super.bind(redSlider.valueProperty(),
                greenSlider.valueProperty(),
                blueSlider.valueProperty());
    }
    @Override
    protected Paint computeValue() {
        return Color.rgb(redSlider.valueProperty().intValue(),
                greenSlider.valueProperty().intValue(),
                blueSlider.valueProperty().intValue());
    }
};
// Bind sampleLine to the Paint Binding object
sampleLine.strokeProperty().bind(colorBinding);
</pre>
<p>So there you have it. Download the <a href="http://www.asgteach.com/download/blog/JavaFX/Draw.java">Sketch Pad (Version 1) JavaFX source code here</a>.</p>
<p>But, what about Version 2? Personally, manipulating three sliders to configure the draw color can be tedious. Version 2 of the Sketch Pad example uses a color picker instead of three sliders for the line color. Stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=272</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaFX Animation and Binding: Using the ProgressBar</title>
		<link>http://www.asgteach.com/blog/?p=219&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javafx-animation-and-binding-using-the-progressbar</link>
		<comments>http://www.asgteach.com/blog/?p=219#comments</comments>
		<pubDate>Wed, 19 Oct 2011 00:31:07 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[JavaFX binding]]></category>
		<category><![CDATA[JavaFX progressbar]]></category>
		<category><![CDATA[timeline]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=219</guid>
		<description><![CDATA[Our previous post describes a JavaFX countdown timer. Let&#8217;s take that same program and add a progress bar control. As the timer counts down, the progress bar gradually fills in—as shown in the screenshot here. When the timer begins (at &#8230; <a href="http://www.asgteach.com/blog/?p=219">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Our <a href="http://www.asgteach.com/blog/?p=334">previous post</a> describes a JavaFX countdown timer. Let&#8217;s take that same program and add a progress bar control. As the timer counts down, the progress bar gradually fills in—as shown in the screenshot here. When the timer begins (at 15), the progress bar is empty (all gray) and when the timer reaches 0, the progress bar is filled in (all blue).</p>
<div id="attachment_220" class="wp-caption alignleft" style="width: 310px"><img class="size-medium wp-image-220" title="FXTimer with Progress Bar" src="http://www.asgteach.com/blog/wp-content/uploads/fxTimerProgress-300x275.jpg" alt="FXTimer with Progress Bar Screenshot" width="300" height="275" /><p class="wp-caption-text">FXTimer with Progress Bar Screenshot</p></div>
<p>The progress bar includes <code>progressProperty</code>, a DoubleProperty with values that range between 0 (no progress or 0% complete) and 1 (progress complete or 100%). Half-way is 0.5.</p>
<p>Recall that in our previous post, we bind the numeric label <code>timerLabel</code> to the timer property (<code>timeSeconds</code>). Now to configure the progress bar, we bind its <code>progressProperty</code> to the timer as well. With binding, we don&#8217;t have to update <code>progressProperty</code> in the timeline&#8217;s event handler.</p>
<p>Here&#8217;s our first attempt.</p>
<pre class="brush: java; title: Listing 1;">
private static final Integer STARTTIME = 15;
private IntegerProperty timeSeconds =
        new SimpleIntegerProperty(STARTTIME);
. . .
// Instantiate progressbar and configure binding
ProgressBar progressBar = new ProgressBar();
progressBar.progressProperty().bind(
                timeSeconds.divide(STARTTIME*1.0));
. . .
// Add to vertical box layout component
vb.getChildren().addAll(button, timerLabel, progressBar);
. . .
</pre>
<p>This is a nice try, but not the result we want at all! We instantiate the progress bar in line 6 and specify its binding in lines 7-8. Recall that <code>timeSeconds</code> is an IntegerProperty, so we must use Property method <code>divide()</code> to make sure the binding is a Double whose range is between 0 and 1. Can you guess the outcome?</p>
<p>There are two problems here. First, because our timer updates once a second, the progress bar chunks through (in 15 evenly spaced chunks) instead of filling smoothly. Second, the progress bar begins filled and empties as the timer counts down (we want the opposite behavior). To fix these problems, we must do the following:</p>
<ul>
<li>Make our timeline cycle faster. Although the label should only change once per second, the progress bar should be updated more often. We do this by making <code>timeSeconds</code> 1500 instead of 15. Then we divide by 100 when binding to <code>timerLabel</code>. </li>
<li>Correlate the starting value of the timer (15) to zero for the progress bar and the ending value of the timer (0) to 1.0 for the progress bar. This <em>fills</em> the progress bar as the timer counts <em>down</em>. (In other words, a little bit of math will help us!)</li>
</ul>
<p>Here&#8217;s the updated code.</p>
<pre class="brush: java; title: Listing 2;">
private static final Integer STARTTIME = 15;
private IntegerProperty timeSeconds =
        new SimpleIntegerProperty(STARTTIME*100);
. . .
// Bind the timerLabel textProperty
// to the timeSeconds property
timerLabel.textProperty().bind(
        timeSeconds.divide(100).asString());
. . .
// Bind the progressBar progressProperty
// to the timeSeconds property
ProgressBar progressBar = new ProgressBar();
progressBar.progressProperty().bind(
        timeSeconds.divide(STARTTIME*100.0)
        .subtract(1).multiply(-1));
. . .
// Inside the button event handler
// Make the timeline duration STARTTIME seconds
timeline.getKeyFrames().add(
        timeSeconds.set((STARTTIME+1)*100);
        timeline = new Timeline();
        timeline.getKeyFrames().add(

                new KeyFrame(Duration.seconds(STARTTIME+1),
                new KeyValue(timeSeconds, 0)));
        timeline.playFromStart();
. . .
</pre>
<p>This provides the behavior we want. Let&#8217;s review these changes.</p>
<ul>
<li>IntegerProperty <code>timeSeconds</code> now starts off at 1500 instead of 15 (100 times the original initial value) (lines 2-3).</li>
<li>To compensate for this change to <code>timeSeconds</code>, we must divide <code>timeSeconds</code> by 100 to correctly configure the <code>timerLabel</code> binding (lines 7-8).</li>
<li>We divide <code>timeSeconds</code> by 1500 to calibrate the progress bar. The values now progress from 0% complete to 100% since we subtract one and multiply by -1 (lines 13-15).</li>
</ul>
<p>Download the FXTimer with ProgressBar <a href="http://asgteach.com/download/blog/JavaFX/FXTimerProgress.java">JavaFX source code here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=219</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>JavaFX Animation and Binding: Simple Countdown Timer</title>
		<link>http://www.asgteach.com/blog/?p=334&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javafx-animation-and-binding-simple-countdown-timer-2</link>
		<comments>http://www.asgteach.com/blog/?p=334#comments</comments>
		<pubDate>Sat, 15 Oct 2011 21:58:54 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[JavaFX binding]]></category>
		<category><![CDATA[timeline]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=334</guid>
		<description><![CDATA[JavaFX has a powerful animation feature that&#8217;s flexible and easy to use. I’m going to build a simple countdown timer that uses animation to countdown a numeric display from 15 (for example) to zero. I can imagine such a timer &#8230; <a href="http://www.asgteach.com/blog/?p=334">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>JavaFX has a powerful animation feature that&#8217;s flexible and easy to use. I’m going to build a simple countdown timer that uses animation to countdown a numeric display from 15 (for example) to zero. I can imagine such a timer in some sort of response game that limits the time you have to make a move (or answer a question).  Our first version will not use binding, but since binding is such an important concept with JavaFX, I will also show you a version that includes binding. And, the approach that uses binding is the correct approach. But, first we&#8217;ll examine how to manually update the numeric display so we can concentrate on the timer code.</p>
<div id="attachment_121" class="wp-caption alignleft" style="width: 350px"><img class="size-full wp-image-121" title="FXTimer Screenshot" src="http://www.asgteach.com/blog/wp-content/uploads/fxTimer_start.jpg" alt="FXTimer Screenshot" width="340" height="312" /><p class="wp-caption-text">FXTimer at Startup</p></div>
<p>Here is a screenshot of the application as it comes up. To start the timer, you click the Start Timer button. The numeric display then counts down—once per second—to zero. Anytime you click the Start Timer button, the timer resets to 15 and restarts the countdown.  <a href="#Listing1">Listing 1</a> shows all of the code except the button&#8217;s event handler code (lines 46-51), which we&#8217;ll see later. Let&#8217;s look at the program structure and the graphical components first.  JavaFX applications extend the <code>Application</code> class and override the <code>start()</code> method. The JavaFX runtime constructs the <code>Application</code> class instance and invokes your <code>start()</code> method. If you use the NetBeans IDE, the IDE will build a skeletal JavaFX application for you. You put your code inside method <code>start()</code>. (Of course, more involved applications will use additional classes defined in other Java files.)  After the class declaration, we declare some class variables such as <code>timeline</code> (Timeline), <code>timerLabel</code> (Label), and <code>timeSeconds</code> (Integer).  Inside method <code>start()</code>, we setup the scene graph. Defining the root node (a Group) and scene and setting the Stage&#8217;s title are part of the boilerplate code the NetBeans IDE provides. We then configure the Label (lines 38-41) and create and configure the Button (lines 43-51). Next, we use a vertical box layout component (VBox) so that the Label and Button are vertically aligned and we center the components horizontally (line 57). As you can see, you add nodes to the scene graph using grouping and layout components methods <code>getChildren().add(<em>node</em>)</code> (for adding a single child node) and <code>getChildren().addAll(<em>nodes</em>)</code> (for adding multiple children nodes). See lines 63 and 65 for examples of <code>addAll()</code> and <code>add()</code>.  I&#8217;ve highlighted Line 39 to show you that we set the label&#8217;s text by converting the Integer <code>timeSeconds</code> to a String. We&#8217;ll then have to perform the same conversion to update the label&#8217;s <code>text</code> when the timer code decrements the counter. <a name="Listing1"></a></p>
<pre class="brush: java; highlight: [39,46,47,48,49,50,51]; title: Listing 1;">
package fxtimer;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

public class FXTimer extends Application {

    // private class constant and some variables
    private static final Integer STARTTIME = 15;
    private Timeline timeline;
    private Label timerLabel = new Label();
    private Integer timeSeconds = STARTTIME;

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Setup the Stage and the Scene (the scene graph)
        primaryStage.setTitle(&quot;FX Timer&quot;);
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250);

        // Configure the Label
        timerLabel.setText(timeSeconds.toString());
        timerLabel.setTextFill(Color.RED);
        timerLabel.setStyle(&quot;-fx-font-size: 4em;&quot;);

        // Create and configure the Button
        Button button = new Button();
        button.setText(&quot;Start Timer&quot;);
        button.setOnAction(new EventHandler() {

            public void handle(ActionEvent event) {
            // Button event handler code goes here . . .
            }
        });

        // Create and configure VBox
        // gap between components is 20
        VBox vb = new VBox(20);
        // center the components within VBox
        vb.setAlignment(Pos.CENTER);
        // Make it as wide as the application frame (scene)
        vb.setPrefWidth(scene.getWidth());
        // Move the VBox down a bit
        vb.setLayoutY(30);
        // Add the button and timerLabel to the VBox
        vb.getChildren().addAll(button, timerLabel);
        // Add the VBox to the root component
        root.getChildren().add(vb);

        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
</pre>
<p>Now for the animation part! <a href="#Listing2">Listing 2</a> shows the code for the Button&#8217;s event handler. When you press the Start Timer button, the runtime invokes the button&#8217;s <code>handle()</code> method. This handler sets up a timeline, which runs indefinitely and cycles once each second. Each time you press the button, the handler stops the timeline if it is active (lines 4-6). The button handler then resets the counter to its initial value (<code>STARTTIME</code>) (line 7), updates the numeric label to match the counter (line 10), and restarts the timeline (line 27).  Okay, so what exactly is a timeline? A Timeline is a JavaFX object you use to define animations by specifying JavaFX object properties that change over time. So, if you want to move a Rectangle object horizontally, you specify different values for the Rectangle&#8217;s x-coordinate property at different times (in different keyframes). A timeline consists of one or more KeyFrames and timelines use these KeyFrame objects to represent the different time frames.  Here, however, we&#8217;re defining a more specialized use case for a Timeline.  After each cycle (when the KeyFrame time slot elapses), the KeyFrame&#8217;s own event handler is invoked.  Now let&#8217;s look at the code that builds and initializes the Timeline object (lines 11-26). We want the timeline to run indefinitely until stopped (line 12).  In this case, we create a single KeyFrame and give it a one second duration (<code>Duration.seconds(1)</code>). We then define an event handler for the KeyFrame, which is executed when the KeyFrame finishes. This means that after one second, the runtime invokes the code in the KeyFrame event handler (lines 17-25).  So what does this KeyFrame event handler do? It decrements our counter. It updates the numeric label. And, if the counter is zero, it stops the timeline. (If the counter is not zero, the timeline restarts automatically because we told it to run indefinitely.) <a name="Listing2"></a></p>
<pre class="brush: java; highlight: [10,20,21]; title: Listing 2—Button Event Handler;">
button.setOnAction(new EventHandler() {  //Button event handler

    public void handle(ActionEvent event) {
        if (timeline != null) {
            timeline.stop();
        }
        timeSeconds = STARTTIME;

        // update timerLabel
        timerLabel.setText(timeSeconds.toString());
        timeline = new Timeline();
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.getKeyFrames().add(
                new KeyFrame(Duration.seconds(1),
                  new EventHandler() {
                    // KeyFrame event handler
                    public void handle(ActionEvent event) {
                        timeSeconds--;
                        // update timerLabel
                        timerLabel.setText(
                              timeSeconds.toString());
                        if (timeSeconds &lt;= 0) {
                            timeline.stop();
                        }
                      }
                }));
        timeline.playFromStart();
    }
});
</pre>
<p><strong>Implementing the Timer with Binding</strong> Note that to properly maintain the numeric label, we had to initialize the label (<a href="#Listing1">Listing 1</a>, Line 39), reinitialize the label during the Start Button event handler (<a href="#Listing2">Listing 2</a>, Line 10), and update the label in the KeyFrame&#8217;s event handler (<a href="#Listing2">Listing 2</a>, Lines 20-21). A better approach is to formally declare that the label&#8217;s text property is dependent on variable <code>timeSeconds</code>. Whenever the value of <code>timeSeconds</code> changes, the <code>timerLabel</code> text also changes. This dependency is called <em>binding</em>.  To implement binding, we change variable <code>timeSeconds</code> from Integer to <code>IntegerProperty</code>. Property types let you bind variables and are new with JavaFX 2.0. Here is the Property declaration for <code>timeSeconds</code>.</p>
<pre class="brush: java; light: true; title: ;">
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
. . .

// Make timeSeconds a Property
private IntegerProperty timeSeconds =
        new SimpleIntegerProperty(STARTTIME);
</pre>
<p>Next, we bind the label&#8217;s text property to <code>timeSeconds</code>, as follows.</p>
<pre class="brush: java; light: true; title: ;">
// Bind the timerLabel text property to the timeSeconds property
timerLabel.textProperty().bind(timeSeconds.asString());
</pre>
<p>This binding creates the desired dependency: the <code>timerLabel</code> label will now show the current value of <code>timeSeconds</code>. Note that we access the <code>timerLabel</code> text property with <code>timerLabel.textProperty()</code>. All JavaFX scene graph nodes use Property types to maintain property values.  With binding in place, we can make several improvements. We remove the code that reinitializes and updates <code>timerLabel</code>. We also remove the KeyFrame&#8217;s event handler and instead animate <code>timeSeconds</code> directly. This means that we specify the ending value for <code>timeSeconds</code> (0) and the timeline will, over the duration of the keyframe, figure out the intermediate values and update <code>timeSeconds</code> accordingly. We no longer decrement <code>timeSeconds</code> manually and no longer play the timeline indefinitely.  We make the duration 15 seconds.  Here is the new, improved button event handler and timeline code. Since <code>timeSeconds</code> is now a Property type, we must use the setters and getters to access its value (line 7). <a name="Listing3"></a></p>
<pre class="brush: java; title: Listing 3—New, Improved Button Event Handler;">
button.setOnAction(new EventHandler() {

    public void handle(ActionEvent event) {
        if (timeline != null) {
            timeline.stop();
        }
        timeSeconds.set(STARTTIME);
        timeline = new Timeline();
        timeline.getKeyFrames().add(
                new KeyFrame(Duration.seconds(STARTTIME+1),
                new KeyValue(timeSeconds, 0)));
        timeline.playFromStart();
    }
});
</pre>
<p>Download the FXTimer with Binding <a href="http://asgteach.com/download/blog/JavaFX/FXTimerBinding.java">JavaFX source code here</a>.</p>
<p>Thanks to <a href="http://blog.netopyr.com/">Michael Heinrichs</a> for his feedback on an earlier version of this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=334</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Return of JavaFX™</title>
		<link>http://www.asgteach.com/blog/?p=101&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-return-of-javafx</link>
		<comments>http://www.asgteach.com/blog/?p=101#comments</comments>
		<pubDate>Thu, 13 Oct 2011 22:21:47 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[JavaFX]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=101</guid>
		<description><![CDATA[JavaFX™, the rich UI design system from Sun Microsystems and then Oracle, never really went away. But JavaFX Script 1.x has been replaced by JavaFX 2.x Java APIs. As a fan of JavaFX script (and co-author of Essential JavaFX—check out &#8230; <a href="http://www.asgteach.com/blog/?p=101">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.asgteach.com/blog/wp-content/uploads/javafx1.jpg"><img class="alignleft size-full wp-image-104" title="javafx" src="http://www.asgteach.com/blog/wp-content/uploads/javafx1.jpg" alt="JavaFX Logo" width="264" height="165" /></a><a href="http://www.javafx.com/">JavaFX™</a>, the rich UI design system from Sun Microsystems and then Oracle, never really went away. But JavaFX Script 1.x has been replaced by JavaFX 2.x Java APIs. As a fan of JavaFX script (and co-author of <em><a href="http://www.asgteach.com/books/javafxbook.html">Essential JavaFX</a></em>—check out <a href="http://www.asgteach.com/javafx/minigolf_launch.htm">Mini Golf</a>), I loved working with many of the unique features that JavaFX provided, such as easy animation, a declarative programming style, type inference, function and sequence types, and a powerful binding mechanism. With JavaFX you create a graphical UI by building a scene graph, a tree structure (or directed <em>acyclic</em> graph) consisting of container nodes and leaf nodes. Container nodes hold other nodes and are used for grouping and layout. Leaf nodes are graphical elements (such as images, lines, text, circles, and so on) that don’t contain other elements.</p>
<p>Oracle announced this new direction at JavaOne 2010. A year later and <a href="http://blogs.oracle.com/javaone/entry/javafx_2_0_arrives_and">JavaFX 2.0 (the Java API system) has been released</a>. Oracle also announced that JavaFX is open sourced. With approximately 50 talks at JavaOne 2011, Oracle sent the message, “We want you to look at this new JavaFX.” So I did look. I am looking.  I am looking and playing and testing. And with all this playing around, I have some mostly good news.</p>
<p>First, for people who have experience with JavaFX script (that is, JavaFX 1.x), many concepts remain the same. You still build a scene graph. You still work with the same familiar graphical objects. You have the same UI controls, but many more. Animation works the same in that you change the value of node properties along a timeline. As before, there are high-level animations, called transitions that simplify animation. By keeping the scene graph and many of the graphical components, JavaFX 2.0 feels familiar. And now I am programming in Java, not JavaFX script. For Java programmers that is very good.</p>
<p>What do I miss? Most of all I miss the easy binding mechanism and the declarative style that makes binding so natural. To be sure, JavaFX 2.0 includes a new Property Binding mechanism that lets you specify binding. It works great. But, it’s not so elegant. JavaFX 2.0 also includes “build” classes that let you create graphical objects using a more declarative style. (I’m not really sure if I’ll use these build classes.)</p>
<p>But back to the good news. Moving JavaFX to Java APIs lets Oracle standardize the system and bring in Java developers. Indeed, FXML lets you specify your scene graph using an XML-based language, which can then be manipulated by UI builder tools. JavaFX 2.0 has an improved event handling model, improved performance (using graphics hardware when available), improved cross-platform support, some 3-D support, and an improved thread model. I am ready to give JavaFX a go! Stay tuned for some example programs coming soon.</p>
<p>Note: To view many of the JavaFX talks presented at JavaOne 2011, see this <a href="http://fxexperience.com/2011/10/javafx-sessions-at-javaone-2011-online/" target="_blank">link</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=101</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iOS Memory Management: Using Autorelease</title>
		<link>http://www.asgteach.com/blog/?p=73&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ios-memory-management-using-autorelease</link>
		<comments>http://www.asgteach.com/blog/?p=73#comments</comments>
		<pubDate>Sun, 05 Jun 2011 18:53:29 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[iPhone/iPad Programming]]></category>
		<category><![CDATA[autorelease]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[release]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=73</guid>
		<description><![CDATA[In a previous post I discussed memory management in iPhone programming. Recall that the iPhone programming environment does not support garbage collection. You must pay attention to objects you create (and therefore own) and must consequently make sure that you &#8230; <a href="http://www.asgteach.com/blog/?p=73">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://www.asgteach.com/blog/?p=11">previous post</a> I discussed memory management in iPhone programming. Recall that the iPhone programming environment does not support garbage collection. You must pay attention to objects you create (and therefore own) and must consequently make sure that you properly relinquish ownership. This permits objects to be deleted from memory correctly. You must also recognize when you use objects that you do not own so that you don’t incorrectly release them.</p>
<p>When you develop for the iPhone (or iPad), you use Apple’s Cocoa Touch framework and you write code with Objective-C. Cocoa Touch supports a Model-View-Controller design and maintains (for you) an Autorelease Pool that temporarily holds objects in memory for later release. So, while it’s true that the iPhone environment does not support automatic garbage collection, the environment does provide some automatic memory management assistance. Understanding how the Autorelease Pool works is essential to fully understanding memory management in Objective-C and the Cocoa Touch environment.</p>
<p>iPhone applications run in an event loop, as shown in the diagram below. That is, when your iPhone application launches, the program enters the event loop and waits for a user touch event. When a touch event happens, the Cocoa Touch framework detects the event, creates an event object, and allocates and initializes an autorelease pool. Cocoa Touch then invokes your application event handler, making the event object available.<br />
<div id="attachment_78" class="wp-caption aligncenter" style="width: 810px"><a href="http://www.asgteach.com/blog/wp-content/uploads/EventLoopDiagram1.gif"><img src="http://www.asgteach.com/blog/wp-content/uploads/EventLoopDiagram1.gif" alt="Event Loop Diagram" title="Event Loop Diagram [Click for larger image]" width="600" height="450" class="size-full wp-image-78" /></a><p class="wp-caption-text">iPhone Application Event Loop</p></div><br />
Your event handler may put objects in the autorelease pool or, perhaps more commonly, use objects that were put into the autorelease pool by other objects. (For example, the <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> convenience method, <span style="font-family:Lucida Console, monospace;font-size:medium">stringWithFormat</span>, creates an autorelease object.)</p>
<p>When your event handler finishes execution, control returns to the Cocoa Touch framework. Cocoa Touch drains the autorelease pool, which sends a <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> message to each object in the pool. Those objects with a retain count of zero are deleted from memory. This means, of course, that just because an object is in an autorelease pool, doesn’t mean that object gets deleted when the pool is drained. Only objects whose retain counts reach zero are deleted.</p>
<p>Cocoa Touch then waits for the next touch event and the cycle begins anew.</p>
<p>So, when should you use autorelease in your code and what do you need to know about autorelease objects?</p>
<p>The most common reason for using autorelease is returning an object you’ve created (and therefore own) to a caller. You can’t release the object inside your method because then you’ll return an invalid object.  On the other hand, if you don’t release the object, you’ll create a memory leak (breaking the basic rule that says you must release objects you own). The solution is to put the object in the autorelease pool. Its release is then delayed until the autorelease pool is drained. Let’s look at an example.</p>
<p>Suppose you have a method <span style="font-family:Lucida Console, monospace;font-size:medium">getLabel</span> in your <span style="font-family:Lucida Console, monospace;font-size:medium">ViewController</span> class that builds an <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> object for a <span style="font-family:Lucida Console, monospace;font-size:medium">UILabel</span> component. An event handler calls this method each time the user taps a button. Here is a first attempt.</p>
<pre class="brush: objc; highlight: [14,15,17]; title: ;">
// Version 1 - Incorrect
- (NSString *)getLabel
{
    NSString * temp;
    if (numberTaps == 1) {
        temp = [[NSString alloc] initWithString:@&quot;time&quot;];
    } else {
        temp = [[NSString alloc] initWithString:@&quot;times&quot;];
    }

    NSString * myLabel = [[NSString alloc] initWithFormat:
			@&quot;You have tapped the button %d %@&quot;,
			numberTaps, temp ];
    [temp release];
    // [myLabel release];   ??
    return myLabel;
    // [myLabel release];   ??
}
</pre>
<p>From our previous post you know that this method is incorrect. Method <span style="font-family:Lucida Console, monospace;font-size:medium">getLabel</span> owns both <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span> and <span style="font-family:Lucida Console, monospace;font-size:medium">myLabel</span> because we create them with <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>. We can release <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span> (just before the return statement), but what about <span style="font-family:Lucida Console, monospace;font-size:medium">myLabel</span>? If you release <span style="font-family:Lucida Console, monospace;font-size:medium">myLabel</span> before the <span style="font-family:Lucida Console, monospace;font-size:medium">return</span> statement, you return an invalid object. However, if you put the <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> after the <span style="font-family:Lucida Console, monospace;font-size:medium">return</span> then the <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> is never executed.</p>
<p>Our second version uses <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> with <span style="font-family:Lucida Console, monospace;font-size:medium">myLabel</span> and <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> with <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span>. Apple recommends that you use <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> instead of <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> whenever possible to keep the size of the pool small.</p>
<pre class="brush: objc; highlight: [14,15]; title: ;">
// Version 2
- (NSString *)getLabel
{
    NSString * temp;
    if (numberTaps == 1) {
        temp = [[NSString alloc] initWithString:@&quot;time&quot;];
    } else {
        temp = [[NSString alloc] initWithString:@&quot;times&quot;];
    }

    NSString * myLabel = [[NSString alloc] initWithFormat:
			@&quot;You have tapped the button %d %@&quot;,
			numberTaps, temp ];
    [temp release];           // delete now
    [myLabel autorelease];    // delete later
    return myLabel;
}
</pre>
<p>This works fine. However, if you nest the <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> call with <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>, <span style="font-family:Lucida Console, monospace;font-size:medium">initWithFormat</span>, and the <span style="font-family:Lucida Console, monospace;font-size:medium">return</span> statement, the resulting code is cleaner and more readable. Here’s our final version. Note that in this version you must use <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> with <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span> instead of <span style="font-family:Lucida Console, monospace;font-size:medium">release</span>.</p>
<pre class="brush: objc; highlight: [10,14]; title: ;">
// Version 3
- (NSString *)getLabel
{
    NSString * temp;
    if (numberTaps == 1) {
        temp = [[NSString alloc] initWithString:@&quot;time&quot;];
    } else {
        temp = [[NSString alloc] initWithString:@&quot;times&quot;];
    }
    [temp autorelease];        // delete later

    return [[[NSString alloc] initWithFormat:
			@&quot;You have tapped the button %d %@&quot;,
			numberTaps, temp ] autorelease];     // delete later
}
</pre>
<p>Let’s review what happens. The program launches and the Cocoa Touch framework waits for a touch event. The user touches a button (for example), and Cocoa Touch creates both the event and the autorelease pool. Cocoa Touch then invokes your application’s event handler. Inside the event handler, your code invokes method <span style="font-family:Lucida Console, monospace;font-size:medium">getLabel</span>. Method <span style="font-family:Lucida Console, monospace;font-size:medium">getLabel</span> creates two <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects, one (<span style="font-family:Lucida Console, monospace;font-size:medium">temp</span>) is used to build the returned <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> and the other is returned to the caller. These <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects have a retain count of 1, since method <span style="font-family:Lucida Console, monospace;font-size:medium">getLabel</span> creates them with <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>.</p>
<p>With method <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span>, these <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects go into the autorelease pool, still with a retain count of 1. Cocoa Touch updates the iPhone screen and drains the autorelease pool. Draining the pool sends a <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> message to our two <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects, which makes their retain counts zero. The <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects are deleted.</p>
<p>(Note that if you need to create many temporary objects you can create your own autorelease pool inside a program loop or method. This technique drains the local pool more often than the standard event loop pool provided by Cocoa Touch and keeps memory consumption low. In this case, all newly <span style="font-family:Lucida Console, monospace;font-size:medium">autoreleased</span> objects now go into this new pool. You should always drain a local autorelease pool in the loop or method in which you allocate it.)</p>
<p>What happens when you obtain an object from an <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> convenience method or one of your own methods that use <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span>, but you want to keep the object around for more than one event cycle?</p>
<p>Good question! In this case, the caller needs to claim ownership of the object with method <span style="font-family:Lucida Console, monospace;font-size:medium">retain</span>. With ownership, you must then make sure that you subsequently release the retained object. We’ll discuss the <span style="font-family:Lucida Console, monospace;font-size:medium">retain</span> method in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=73</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>iOS Memory Leaks? Program Crashes? Start Here!</title>
		<link>http://www.asgteach.com/blog/?p=11&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ios-memory-leaks-program-crashes-start-here</link>
		<comments>http://www.asgteach.com/blog/?p=11#comments</comments>
		<pubDate>Tue, 31 May 2011 18:38:21 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[iPhone/iPad Programming]]></category>
		<category><![CDATA[alloc]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[release]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=11</guid>
		<description><![CDATA[So, you want to write applications for the iPhone and/or iPad? I do! And, with a background in software engineering, Java, C++ and yes, even plain old C, I thought I’d take the plunge. As I’ve learned about Apple’s software, &#8230; <a href="http://www.asgteach.com/blog/?p=11">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So, you want to write applications for the iPhone and/or iPad? I do! And, with a background in software engineering, Java, C++ and yes, even plain old C, I thought I’d take the plunge. As I’ve learned about Apple’s software, I’ve come to appreciate its overall design, its use of patterns, and its maturity.</p>
<p>But, don’t think you can forget the nitty-gritty details of pointers, memory management, and good programming practices. Those of you out there with experience in Java and Java’s garbage collection: take heed. The iPhone programming environment does <em>not</em> support garbage collection. This means you must understand the iOS memory management model.</p>
<p>Thus, we begin our exploration of iOS with the iOS memory management scheme. The rules for correct handling of objects’ memory are clear, but often, individual cases can cause confusion. Let’s start with the basic rule:</p>
<blockquote><p><span style="font-style:normal">If you own an object, you are responsible for relinquishing ownership when you’re done with it. And, if you don’t own an object, you better not relinquish ownership. (This is like selling a car that you don’t own—somebody is going to be very unhappy when they find out you don’t have the pink slip.)</span></p></blockquote>
<p>How do you own an object and how do you relinquish ownership?</p>
<p>You own an object when you’ve created it with a method that begins with <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>, <span style="font-family:Lucida Console, monospace;font-size:medium">new</span>, <span style="font-family:Lucida Console, monospace;font-size:medium">copy</span> or <span style="font-family:Lucida Console, monospace;font-size:medium">mutableCopy</span>.</p>
<p>You can also own an object by sending it the <span style="font-family:Lucida Console, monospace;font-size:medium">retain</span> message.</p>
<p>You relinquish ownership by sending the object either the <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> or <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> message. You use <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> when you need to relinquish ownership, but you don’t want the object to be released from memory just yet. This will be discussed in another post.</p>
<p>Behind the scenes, all objects have reference counts (called <em>retain</em> counts in iOS). When you create an object, its retain count is 1. When you send an object the <span style="font-family:Lucida Console, monospace;font-size:medium">retain</span> message, its retain count increments by 1. When you send an object the <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> message, its retain count decrements by 1. If an object’s retain count becomes zero, the system deletes the object from memory.</p>
<p>If you fail to relinquish ownership of an object you own, its retain count won’t ever reach zero and the object is never deleted from memory. This creates a memory leak. The problem becomes worse if the programming error is repeated because the object is created over and over again without a subsequent release.</p>
<p>If you relinquish an object that you don’t own and the object’s retain count becomes zero prematurely, your application may crash when you attempt to send a message to an object that has been deleted from memory.</p>
<p>Let’s look at some examples. Our first example creates a mutable array (using collection class <span style="font-family:Lucida Console, monospace;font-size:medium">NSMutableArray</span>) and adds three <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects to it with message <span style="font-family:Lucida Console, monospace;font-size:medium">addObject</span>. We print the contents of the array and then release ownership.</p>
<pre class="brush: objc; title: ;">
NSMutableArray *projects = [[NSMutableArray alloc] init];
[projects addObject:@&quot;My Project&quot;];
[projects addObject:@&quot;Your Project&quot;];
[projects addObject:@&quot;Joe's Project&quot;];

NSLog(@&quot;Projects = %@&quot;, projects);        // display
[projects release];                // relinquish ownership
</pre>
<p>Note that we’ve taken ownership of collection <span style="font-family:Lucida Console, monospace;font-size:medium">projects</span> because we created it with method <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>. We then relinquish ownership (as we must) by sending it message <span style="font-family:Lucida Console, monospace;font-size:medium">release</span>. Here is the output.</p>
<pre class="brush: plain; light: true; title: ;">
Projects=(
    My Project,
    Your Project,
    Joe's Project
)
</pre>
<p>This is straightforward. Now let’s add the following code (highlighted below). We assign variable <span style="font-family:Lucida Console, monospace;font-size:medium">myProject</span> to the <span style="font-family:Lucida Console, monospace;font-size:medium">projects</span> object at index 0 and display this object.</p>
<pre class="brush: objc; first-line: 6; highlight: [7,8]; title: ;">
    NSLog(@&quot;Projects=%@&quot;, projects);
    NSString * myProject = [projects objectAtIndex:0];
    NSLog(@&quot;my project = %@&quot;, myProject);
    [projects release];
</pre>
<p>Here is the updated output.</p>
<pre class="brush: plain; light: true; title: ;">
Projects=(
    My Project,
    Your Project,
    Joe's Project
)
my project = My Project
</pre>
<p>Should we relinquish ownership of object <span style="font-family:Lucida Console, monospace;font-size:medium">myProject</span>? No, we must not. We do not own the object pointed to by <span style="font-family:Lucida Console, monospace;font-size:medium">myProject</span>. If we were to relinquish ownership, we would incorrectly decrement the reference count for the simple reason that the caller here does not own the object.</p>
<p>Well then, who owns the object pointed to by <span style="font-family:Lucida Console, monospace;font-size:medium">myProject</span>? The answer is the <span style="font-family:Lucida Console, monospace;font-size:medium">projects</span> collection is the owner.  When you add an object to a collection, the collection takes ownership of that object. Then, when a collection class is deallocated, it relinquishes ownership of each object it contains. Similarly, if you remove an object from a collection, the collection relinquishes ownership. Simply accessing an object from a collection, however, (for example with message <span style="font-family:Lucida Console, monospace;font-size:medium">objectAtIndex</span>) does not constitute acquiring ownership by the caller.</p>
<p>Let’s look at another example. Here we build <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> objects in a loop and store each one in the <span style="font-family:Lucida Console, monospace;font-size:medium">projects</span> collection.</p>
<pre class="brush: objc; title: ;">
NSMutableArray *projects = [[NSMutableArray alloc] init];

for (int i = 0; i &lt; 3; i++)
{
    NSString * temp = [[NSString alloc]
               initWithFormat:@&quot;Project%d&quot;, i];
    [projects addObject:temp];
}

NSLog(@&quot;Projects=%@&quot;, projects);
[projects release];
</pre>
<p>Here is the output.</p>
<pre class="brush: plain; light: true; title: ;">
Projects=(
    Project0,
    Project1,
    Project2
)
</pre>
<p>Can you identify the problem here? Look at the <span style="font-family:Lucida Console, monospace;font-size:medium">for</span> loop. We create an <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> object with message <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>, which means we have ownership of the object pointed to by <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span>. We then add the object to the collection. At this point, the object pointed to by <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span> has a retain count of 2—one because we created it using <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span> and two because the collection claims ownership when we add the object to the collection.</p>
<p>When the collection is deallocated, the collection class sends a <span style="font-family:Lucida Console, monospace;font-size:medium">release</span> message to each object in its collection. These objects will then all have a retain count of 1. But since we don’t ever (incorrectly) relinquish ownership, these objects are not properly released and the retain count never reaches zero. We have a memory leak!</p>
<p>The solution is to release each object after adding it to the collection.</p>
<pre class="brush: objc; first-line: 3; highlight: [8]; title: ;">
for (int i = 0; i &lt; 3; i++)
{
    NSString * temp = [[NSString alloc]
               initWithFormat:@&quot;Project%d&quot;, i];     // ownership
    [projects addObject:temp];
    [temp release];               // relinquish
}
</pre>
<p>Here is a final example that uses a variation of this code.</p>
<pre class="brush: objc; title: ;">
NSMutableArray *projects = [[NSMutableArray alloc] init];

for (int i = 0; i &lt; 3; i++)
{
    NSString * temp =
               [NSString stringWithFormat:@&quot;Project %d&quot;, i];
    [projects addObject:temp];
}

NSLog(@&quot;Projects=%@&quot;, projects);
[projects release];
</pre>
<p>This time we’ve left off the release of <span style="font-family:Lucida Console, monospace;font-size:medium">temp</span> inside the <span style="font-family:Lucida Console, monospace;font-size:medium">for</span> loop. Is this correct? Let’s return to the original rule, which says if we create an object with a message that starts with <span style="font-family:Lucida Console, monospace;font-size:medium">alloc</span>, <span style="font-family:Lucida Console, monospace;font-size:medium">new</span>, <span style="font-family:Lucida Console, monospace;font-size:medium">copy</span>, or <span style="font-family:Lucida Console, monospace;font-size:medium">mutableCopy</span>, then we must claim ownership. Here, we create each <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> object with message <span style="font-family:Lucida Console, monospace;font-size:medium">stringWithFormat</span>. In this case, we must not claim ownership and therefore, must not relinquish ownership with message <span style="font-family:Lucida Console, monospace;font-size:medium">release</span>. The above code is correct.</p>
<p>In the next post, I’ll discuss message <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span>. I’ll explain how <span style="font-family:Lucida Console, monospace;font-size:medium">NSString</span> can (for example) correctly manage the memory of objects it creates using convenience methods such as <span style="font-family:Lucida Console, monospace;font-size:medium">stringWithFormat</span>. I’ll also show you how you can use <span style="font-family:Lucida Console, monospace;font-size:medium">autorelease</span> to correctly manage your own objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=11</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Welcome!</title>
		<link>http://www.asgteach.com/blog/?p=7&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=welcome</link>
		<comments>http://www.asgteach.com/blog/?p=7#comments</comments>
		<pubDate>Sat, 30 Apr 2011 23:52:48 +0000</pubDate>
		<dc:creator>Gail</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.asgteach.com/blog/?p=7</guid>
		<description><![CDATA[We are busy creating content for our new blog. Stay tuned and please check back soon!]]></description>
			<content:encoded><![CDATA[<p>We are busy creating content for our new blog. Stay tuned and please check back soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.asgteach.com/blog/?feed=rss2&#038;p=7</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

