javakiddy's blog en JavaFX, Android, and the psychic octopus <!-- | 0 --><p>Surely one of the biggest announcements at JavaOne 2010 was the new roadmap for JavaFX, laying out the journey towards a 2.0 release that will be radically different from what had gone before -- not so much evolution, as total revolution. While the details, when they arrived, contained a fair few surprises, the overall radical nature of the roadmap was not totally unexpected; many had suspected <em>some</em> kind of upheaval was on the cards. Since its inception, JavaFX had struggled to define itself within the Java community, upsetting some and bamboozling others. Even the 2.0 roadmap announcement was met with some confusion on Twitter [<a href="">1</a>][<a href="">2</a>][<a href="">3</a>], although eventually most tweeters seemed to get the message.</p> <p>It would seem the about-turn is a reflection of a shift in the way Oracle wants Java to approach Rich Internet Applications in future, combined with a reality check regarding the limitations of the technology for API coding. No doubt the love-it-or-hate-it feedback JFX seemed to garner from the Java community also played its part in the decision.</p> <p>Two points in the JavaFX 2.0 roadmap particularly caught the imagination of the Twittersphere. Firstly, the JavaFX Script language is to be discontinued as an official Oracle project, and secondly, the key language features and API (scene graph, binding, sequences, etc.) are to be re-engineered into regular Java APIs, making them accessible to languages other than JavaFX Script.</p> <p>I have to say I'm sad to see JavaFX Script get dropped (and not just for <a href="">the obvious reason</a>), although as an open source compiler this probably won't be the last we see of it. Dropping official support, however, does mean the language won't necessarily benefit from the full time expertise of so many developers skilled in the art of compiler writing. Going forward, for the language to survive it has to attract the attention of not only graphics enthusiasts, but language specialists too.</p> <p>JavaFX Script was an attempt to create a DSL (domain specific language) for user interface coding and animation. For those readers who've never dabbled in the black arts of graphics and animation, let me explain: traditionally the GUI programmer uses a general purpose language (or, at least, a language designed for something other than creating GUIs) with a set of graphics/UI APIs sellotaped crudely onto the side. Unlike Java, or C++, or Groovy, or JavaScript, or [insert your favourite here], JavaFX Script was a purpose made language intended to address directly (and grow with) the needs of the GUI developer. Unfortunately its greatest strength was also its greatest weakness: JavaFX Script was <a href="">not a great general purpose language</a>, and you need a solid general purpose language to create APIs. So the opening up of JavaFX to Java and other JVM languages was a very positive step. Ideally the JavaFX APIs would be built in Java, leaving the JavaFX Script language free to do what it does best: create great user interfaces.</p> <p>I doubt there were enough desktop programmers in the Java community to truly appreciate the benefit of a DSL like JavaFX Script (more on this point later), and so faced with a barrage of &quot;why didn't you use Groovy?, why didn't you use Scala?&quot;, I guess JavaFX Script's days were numbered.</p> <p>But in a wider sense the change in direction heralded by the new roadmap has, I think, ramifications far beyond just dropping JavaFX Script and re-purposing the APIs to work with Java. In this blog entry I want to examine why JavaFX 1.x divided so many, and consider how the new 2.0 roadmap fits into the current (and future) landscape of RIAs.</p> <h3>Ten ton gorillas</h3> <p>Since the introduction of the first Enterprise Edition, Java has been a heavily lopsided community. The Standard Edition and Micro Edition have always found themselves starved of heat and light, living as they do in the hard shadow of their Goliath enterprise sibling. The gravity field surrounding EE is so great, it even crushed ME, despite ME&rsquo;s massive initial market penetration. Treated almost as a curious sideshow attraction by the majority of the Java community, ME's growing pains were never addressed in a timely fashion, and its future never seemed to be a priority. I can't think of any other technology that fell quite so far through events of its own making -- even Netscape had the excuse of anti-competitive practices by a major rival!</p> <p>Likewise, desktop Java has its own woeful tale of neglect (although, to be honest, other complications also conspired to limit its success). JavaFX was supposed to be a brave attempt to address that, to create something new and future facing, ensuring Java&rsquo;s place at the top table in the second decade of the 21st century. So, naturally, almost everyone in the Java community treated it with deep suspicion!</p> <p>The EE guys looked at JavaFX and wondered &quot;how can I build a web site out of <strong>that</strong>?!&quot; (an understandable reaction, given some of them seem to be blissfully unaware anything exists outside of a web browser). The ME folks wanted to know when it would run on a device they might actually have heard of. And the SE clan were mad as hell that the limited Java desktop bodies at Sun/Oracle were not busying themselves adding to Swing.</p> <p>Of course, of all of these groups it would be the EE people who would ultimately determine the fate of JavaFX, simply because they dominate the community. Naturally they have a highly myopic view of the way software should be written for the internet, a view that sees the browser at the heart of the user experience (no doubt reinforced by over fifteen years of everything being browser based). To sell the EE folks a technology that looked beyond their browser centric worldview was always going to be tough. Many, after all, languished under the impression that HTML 5 had already been anointed as <em>the</em> platform for the next-gen Rich Internet Applications -- case closed!</p> <h3>Red Herrings</h3> <p>In term of building application GUIs, the problem with the web browser is (unlike <em>proper</em> UI/graphics toolkits) it only has one layout paradigm &mdash; the flow. Granted, it boasts the mother of all flow layout engines -- not so much &quot;everything but the kitchen sink&quot;, more like &quot;everything including the kitchen sink, plus a kitchen sink we robbed from next door when they took that two week vacation!&quot;. But there&rsquo;s no getting away from the fact the browser sees everything as nested blocks of flowing content on a page, much like a desktop publisher; and the page/paragraph model is certainly <strong>not</strong> the way professional GUIs are created.</p> <p>With its limited GUI capabilities, stateless protocols, and love of server round-trips, the web browser is an excellent choice for applications centred on a basic label/value form, wrapping a CRUD data model (create/read/update/delete, the record-based philosophy of all popular databases). Once you step away from basic forms and CRUD, however, you find the experience gets progressively less agreeable. The more sophisticated the UI, the greater the challenge to pull it off in HTML. And I say this not as an ignorant onlooker, but as someone who spends their working day coding with browser based visualisation tools like the <a href="">Exhibit</a> semantic web components from MIT's Simile project.</p> <p>Many believe HTML 5 will elevate the browser to become a fully fledged RIA technology. They seem to think that, like some cheap televangelist, HTML 5 will magically raise the browser from its seat, invite it to throw away its crutches, and have it doing cartwheels around the room. Undoubtedly HTML 5 adds many useful app-centric features to the browser, but it&rsquo;s still very immature and I suspect will always be a pain to get working across multiple browsers (the label &quot;write once, debug everywhere&quot; is more true here than anywhere else!) You may have been wowed by the latest IE9 showcase app [<a href="">1</a>][<a href="">2</a>], but the kind of effects IE9 is (just about) able to produce on a web page are already run of the mill for the purpose-made retained mode graphics engines driving Flash, Silverlight or JavaFX.</p> <p>Ultimately the promise of HTML 5 and Canvas is that, at some unspecified point in the future, the browser may be able to offer the same kind of UI richness as already enjoyed today by the iPhone, Flash, JavaFX, etc. (Of course, by the time HTML 5 catches up, who knows where iPhone, Flash... will be?)</p> <p>So will the browser be the future of RIAs? Despite its limitations, the browser has undeniably one major advantage: it is massively popular with end users. Every internet device has a web browser, and every user knows how to use it. More importantly, the web makes it easy to find and share applications: everything lives at the end of a URL. That familiarity has served the browser well, so many naturally assume this domination will extend into the future -- RIAs will be browser based, the web has won, end of story!</p> <p>But one fateful day in July 2008 changed all that...</p> <h3>Clairvoyant octopuses</h3> <p>July 11th 2008 (so says Wikipedia) was the day the iPhone App Store opened its doors for the first time, and nothing was quite the same thereafter!</p> <p>Previously Apple CEO, Steve Jobs, had insisted the way to write apps for the company&rsquo;s iPhone was via the Safari browser -- Jobs was backing very firmly HTML 5 and web standards. (Ironic, given what later transpired.) After pressure from developers, however, Apple released an SDK for native iPhone apps, and in July 2008 the first apps started to arrive. iPhone owners quickly voted with their fingertips, and the App Store became an overnight smash hit. All talk of HTML 5 was abandoned, as the App Store became the undisputed USP (unique selling point) of the iPhone product range. And when it became known some developers were getting rich from their iPhone apps -- seriously rich! -- ever more programmers flooded onto the platform, creating a mini gold rush.</p> <p>Android arrived, bringing the app experience to non-Apple devices, and it too proved to be a success. This was clearly not just a fluke!</p> <p>What the App Store and Android Market proved was that the web browser was not the only way users wanted to consume their internet apps. The certainty that the browser, and HTML 5, were the sure-fire victors in the RIA race was challenged; now developers had to decided: which skill would be more in demand in five years time, HTML 5/Canvas or iPhone/Android?</p> <p>As a web developer it would be all too easy to dismiss the success of the app store model as being localised to smart phones. Sure, phones have apps, but laptops and desktops will always have the browser and HTML, right? But the rise of the tablet has muddied even these waters. Devices like the iPad and Galaxy Tab create bridges between the mobile and desktop space -- if the app store model takes hold on tablets, then how long will it be before the desktop falls for the charms of a store model? Today when you meet with a client to flesh out the requirements for their new online app you ask &quot;which browsers would you like to support?&quot;. Tomorrow you may well be asking &quot;do you want iOS, Android, or both?&quot;</p> <p>Of course the game is still in play, and nobody (except, perhaps, Paul the Psychic Octopus) knows for sure what the end result will be. Personally I will be paying close attention to the tablet space. If tablet users access Facebook and Twitter via a web browser then perhaps HTML 5 will have a future as an application platform. If they instead opt for downloading Facebook or Twitter apps, then those with a heavily web centric skillset had better watch out, as the web could start to revert once more to just a hypertext technology.</p> <p>(Note: I'm not suggesting either technology will vanish without trace, but history has taught us that when two technologies are in direct competition, sooner or later one starts to dominate.)</p> <h3>Dead parrots (or any they just pining for the fjords?)</h3> <p>So where does all this leave JavaFX?</p> <p>While the dropping of JavaFX Script and the moving of the JavaFX APIs to Java generated the most chatter, two other points in the 2.0 roadmap are probably more important for the future of the technology. First, JavaFX Mobile is to be shelved in favour of an <a href="">update to Java ME</a>. Second, the JavaFX graphics APIs are eventually going to be able to target HTML 5.</p> <p>In light of events post July 2008, this seems like a decidedly odd decision.</p> <p>JavaFX 1.0 was a technology firmly in the native apps mold. But 2.0 seems to be doing 180 degree about face to re-engineer JavaFX for the HTML 5 crowd. Yes, judging by the roadmap it seems JavaFX 2.0 will still be able to target native apps -- but without credible API support extending onto mobile devices (like smart phones and tablets), how can it possibly fit in with Google's Android or Apple's iOS? Surely this couldn't be yet another example of Enterprise Edition's massive gravitational field, sucking everything within close range towards its web centric worldview, while crushing anything that cannot adapt?</p> <p>It's true JavaFX in its 1.0 form didn't acquire the traction Sun had wanted. (I'm too much of a fan to admit it failed, so let's just agree to say it wasn't as successful as some had hoped!) The dropping of JavaFX Mobile, and with it the &quot;all the screens of your life&quot; agenda, I'm sure was done for pragmatic reasons. But it leaves JavaFX looking decidedly anemic in a possible future were apps may be expected to run across phones, tablets and desktops. Under 1.x there was still a hope JavaFX might find its way onto Android (once current difficulties had been sorted out), meaning it would span all three form factors. Under 2.0 it looks (assuming I've understood the details right) like we're retreating back to separate and distinct SE and ME platforms, with select JavaFX enhancements being added to each.</p> <p>On the desktop JavaFX 2.0 will be able to work directly with the native graphics hardware (via the Prism stack) or indirectly via HTML 5. Rather than try to ride both horses at once, I think Oracle should choose whether it wants to back a native model of RIAs (a la Android/iOS), or the web model (a la HTML 5), then decisively engineer JavaFX towards that goal. What I'm particularly concerned about is the effort to port the scene graph APIs onto HTML 5 will consume so much of the JFX team's resources and prove so problematic (<em>write once, debug everywhere</em>) that it will act as a ball and chain to limit innovation and slow down growth.</p> <p>Ultimately, for me, the 2.0 roadmap threw up more questions than it answered. If JavaFX is no longer to be for all the screens of our life, what is it good for? Is it merely for adding snazzy animations to Swing applications, or is it a replacement for Swing itself? (The answer is apparently &quot;<a href="">the latter</a>&quot;.) If JavaFX is no longer required to run on phones, do we need a new UI? -- couldn't we just add a CSS skinnable PLaF to Swing? Of course the obvious answer is the Swing components don't lend themselves to being manipulated in a scene graph, but how often does one honestly need to spin a progress bar through 360 degrees, or apply a blur effect to a file selector?</p> <p>With the announcement of the roadmap JavaFX has effectively been plunged back into pre-release beta. The transition from JavaFX 1.3 to 2.0 is far from clear; if I commit to 1.3 now, will I be able to move smoothly over to 2.0 (using the open source JavaFX Script compiler), or will the Java-ized APIs be sufficiently different to the JavaFX originals? Even if the answers to questions like these are favourable, I suspect the roadmap has killed JavaFX dead for the time being (how can anyone commit a major project to any technology destined for serious overhaul in less than 12 months?)</p> <p>While I recognise the pragmatism behind the roadmap's decisions (even if I don't necessarily agree with all its conclusions) the most frustrating part is JavaFX fanboys (guilty!) are now back to the familiar wait-and-see game, biding our time and twiddling our thumbs before we can start over with the new re-imagined platform.</p> <p>Although I've never pretended everything in the JavaFX garden was rosy, I have always been (and hope to remain) a JavaFX fan. I sincerely wish the development team all the best as they push forward into the uncharted realms of 2.0, and nothing would give me greater pleasure than to see a healthy JavaFX 2.0 dominating the RIA space, coupled with a strong and vibrant JavaFX Script community. But I have this uneasy feeling that the app store will win out (admittedly, no psychic octopus has yet ruled on the matter), and 2.0 seems to be a move away from that model (or, at the very least, a significant distraction in the form of supporting HTML 5).</p> <p>That's all I have to say on the matter for now. But I'll leave you with one final thought: given Android doesn't really have a native retained mode graphics stack, and relies upon separate XML files for its declarative UI support, wouldn't it be a bittersweet irony (from Oracle's point of view) if an open sourced JavaFX Script found favour with Android developers, coupled with an Android specific scene graph, to create the kind of rich user interfaces that Chris Oliver originally intended for Java?</p> <p>Now, does anyone know if Paul the Octopus is contactable on Twitter?. I have a few questions... :)</p> Blogs GUI Java Desktop JavaOne Swing Web Applications Fri, 24 Sep 2010 13:13:52 +0000 javakiddy 487826 at Apple iPad Not So Flash <!-- | 0 --><p>Amidst all the hype of the Sun to Oracle transition over the last week, some of you may have missed a certain announcement by a Cupertino-based firm regarding the imminent release of a computing device they say will fill the gap between netbooks and laptops. The Apple iPad is not, <a href="">as some onlookers first suspected</a>, a innovative feminine hygiene product, but a tablet device promising to offer (to quote Apple CEO Steve Jobs) &quot;the best browsing experience you've ever had&quot;.</p> <p>But &quot;the best browsing experience&quot; does not include web plugins it seems, as despite the iPad's 1024x768 screen, 1Ghz processor, and support for wireless connectivity, it is destined to be bereft of Flash, Silverlight, and (everyone's favourite in this neck of the woods) Java.</p> <p>These omissions, particularly Flash, have caused some degree of controversy online, but why is Apple thumbing its nose at plugins?</p> <p>Since the iPad product announcement the Flash debate has been raging across the blogosphere, on both <a href="">pro-Apple</a> and <a"" href="">pro-Adobe</a> sites. As you'd expect, the Adobe fans point to the prominence of Flash on the web, its use for games, video, and rich interactive content. This is undeniably true -- even Jobs' own carefully crafted iPad introduction quickly stumbled across a <a href="">couple of examples of missing Flash content</a> as he demonstrated browsing the web, although he was careful to ensure the tell-tale blue Lego logos were quickly scrolled out of view.</p> <p>Apple fans respond by echoing Steve Jobs' own <a href="">alleged comments</a> that Abobe are lazy and produce crash-prone software. The iPad is better off without Flash. they say, because data gathered by Apple's crash reporting tools has shown the plugin is the single greatest source of Safari crashes, and its video playback is far too CPU-hungry.</p> <p>Besides, isn't HTML5 the future?</p> <p>These responses ignore a few simple facts. For a start Flash's high ranking in the crash report statistics could surely be explained by its overwhelming popularity on the web. Plugin systems, by their very nature, seem to be particularly prone to crashing -- for reasons far too numerous to list here trying to embed one application inside another, seamlessly and without either tripping the other up, has always been a particularly difficult trick to pull off. This is especially true of desktop software, where the thick and complex code glue that usually binds the two independent GUIs together and keeps them in sync often has to keep up with the erratic actions of the user. The question is this: when the stats are adjusted to account for popularity, is Flash any worse than other plugins?</p> <p>And as for Flash's video playback being slow, the reason for this, <a href="">according to Adobe</a> (click &quot;Product Details&quot;), is because Apple refuses to expose the required APIs for hardware optimised decoding -- presumably they would prefer everyone to take the QuickTime route for video.</p> <p>But what of the final charge against Flash, that it's obsolete now HTML5 has arrived? This relates specifically to Flash's use on sites like YouTube to play video. Even if for argument's sake we accept this as true, it ignores Flash's other numerous features, and it doesn't explain why Java is also missing.</p> <p>i-Apologists have a simple answer for this: Apple is trying to defend the freedom of the web by taking a stand against closed source. They <a href="">paint Apple</a> is a knight in shining armour, with HTML5 its Excalibur, engaging in an ideological crusade against the evil forces of proprietary software (non-Apple proprietary software, naturally!) that seek to enslave the good citizens of the web.&nbsp;To defend everyone from the tyranny of Flash and its fellow freedom-hating plugins, Apple (our hero!) has banished them into the wilderness -- anyone suggesting this is a bit like fighting totalitarianism by burning all books that don't advocate democracy will be thrown in the dungeons! (Although these being Apple i-Dungeons, they probably have nice shiny walls and brushed metal trim on the thumb screws...)</p> <p>The iPhone's limited 3G connection at least presented a plausible excuse for its lack of Flash -- but on the iPad (a Wi-Fi device being promoted as &quot;the best browsing experience you've ever had&quot;) its continued non-presence looks more than a little absurd. Is this really the result of Steve Jobs' desire to keep the web open? I, for one, doubt it!</p> <p>Apple makes substantial profit from selling software through its app store; this revenue stream would be severely compromised by rival (and free) application and media playing platforms like Flash, Silverlight, or our own JavaFX. We've become accustomed to walled gardens on cell phones, simply because of the limited nature of the hardware and networks (although how long this will last in the age of the smart phone is anyone's guess), but the iPad is distinctly not a phone, it is being pitched into the space between netbooks and laptops, an arena where the consumer does not expect to encounter walled gardens. (And remember, this is an artificial barrier, not created by the technical limitations of the device but the desire of the manufacturer to drive content towards their revenue creating services -- perhaps the iPad should be renamed the i-Pay?!)</p> <p>Ultimately it could be said that Apple is just exercising its right to put out a products as it sees fit, and this is undeniably true. And consumers, after all, don't have to buy the iPad! But if we're talking about freedom of expression here, surely it is my (and other's) right to exercise free speech by commenting on their decisions, or indeed asking questions about the wider issue: should companies like this be allowed to arbitrarily block software applications and platforms from their devices?</p> <p>A decade ago Microsoft was dragged into court by the US Department of Justice for taking advantage of its privileged position as an operating system maker to heavily promote and favour its own products. But Microsoft at no point banned Netscape, Java, or other competing products from Windows computers. It tried to influence new users towards its own products by pre-installing them and giving them high visibility on the desktop, but ultimately the end user was free to ignore the Microsoft choice and install an alternative instead. Not so with the iPad, it seems!</p> <p>I guess what I'm trying to say is, while I admire the style and innovation Apple bring to each product, the political baggage they're starting to accumulate is really beginning to turn me off. And perhaps I don't like the message it sends out should the iPad prove to be successful -- that manufacturers, not consumers, should choose which software platforms run on their devices. As the Java community finally seems to be on the verge of getting the client facing tools it needs (JavaFX and its associated designers/editors), perhaps I dread the thought of being locked out of the next generation of devices.</p> Blogs Embedded Tue, 02 Feb 2010 03:38:01 +0000 javakiddy 342668 at Thinking Declaratively in JavaFX <!-- | 0 --><p>JavaOne is coming up, and with it no doubt a slew of enhancements to JavaFX. Many of you reading will have no doubt dipped your toe into the waters of Sun's new platform, but how well do you really understand the power of its <a href="">Domain-specific language</a>, JavaFX Script?</p> <p>I've had a pretty good <a href="">excuse to write lots of JavaFX code of late</a>, and to be exposed to some of the difficulties programmers first have when approaching the language. One of the common stumbling blocks seems to involve the shift in thinking from purely procedural source code (where the function/method is our chief currency) to the declarative source code supported by JavaFX Script (where code may be nested into a tree structure).</p> <p>So, what I'm going to do in this post is take a problem ripe for <i>declarative exploitation</i>, and show how JavaFX Script might change the way we tackle the solution. For newbies struggling to understand the power of JavaFX, hopefully this will be an eye opener. For the uninitiated, perhaps it might demonstrate how JavaFX Script differs from Java and other languages.</p> <p>The example I've chosen is the parsing of an XML file — a simple enough task one might think, but a task which highlights the stark contrasts between the structure of the document being processed, and the structure of the source code processing it. (Hopefully that last sentence will make a bit more sense by the time you've finished reading this posting!)</p> <p>To parse XML in JavaFX we would typically reach for the <code class="prettyprint"></code> class. <code class="prettyprint">PullParser</code> walks the document from start to finish, breaking the XML up into a stream of events: for opening tags, for closing tags, and for any loose text inside them. We register a function to receive the events as they come in, and do with them as is our wont. It all seems very straight forward, so where's the problem?</p> <p>Consider the (slightly contrived) XML below:</p> <pre class="prettyprint"><code><?xml version="1.0" ?><br /><shop><br />    <version>1</version><br />    <title>Shop example</title><br />    <customers><br />        <customer><br />            <name>Joe Smith</name><br />            <address>123 Java Street</address><br />        </customer><br />        <customer><br />            <name>Fred Bloggs</name><br />            <address>456 Duke Road</address><br />        </customer><br />    </customers><br />    <products><br />        <product><br />            <name>Widget Maker</name><br />            <price>20 groats</price><br />        </product><br />        <product><br />            <name>Chocolate Fireguard</name><br />            <price>99 credits</price><br />        </product><br />    </products><br /></shop></code></pre> <p>Both <code class="prettyprint"><customer></code> and <code class="prettyprint"><product></code> contain <code class="prettyprint"><name></code> elements, and both <code class="prettyprint"><name></code> elements are at the same level in the document. JavaFX's <code class="prettyprint">PullParser</code> tells us about the element causing the event, but little of where the element is in the document as a whole (aside from its level). This results in long blocks of conditional code, along the lines of...</p> <blockquote><p>If the event is a 'text' event, and our immediate parent is <code class="prettyprint"><name></code>, and it was at level 3 in the document, and its parent was <code class="prettyprint"><customer></code>...</p></blockquote> <p>A bit of a mouthful, just to ensure we know which bit of text in the XML we're processing. And remember, the only way of knowing the <i>lineage</i> of an event is to keep track of where we are in the document ourselves.</p> <p>Things get even messier when we want to populate objects as we process the XML. Suppose we created a couple of classes, one to hold customer details, the other to hold product details, and we intend to populate and store objects of these classes as we walk over the XML.</p> <pre class="prettyprint"><code>class Customer {<br />    var name:String;<br />    var address:String;<br />}<br />class Product {<br />    var name:String;<br />    var price:String;<br />}<br /><br />var title:String;<br />var customers:Customer[];<br />var products:Product[];</code></pre> <p>Because each XML element is delivered as separate, discrete, events we can't use a local <code class="prettyprint">Customer</code>/<code class="prettyprint">Product</code> object; any objects we create must persist over multiple event function calls, giving us little alternative but to use private instance variables for this temporary data.</p> <p>For any non-trivial XML document the event handling code quickly grows in complexity and acquires a burgeoning collection of private variables for maintaining state. The code starts to become a tad spaghetti-like, and inflexible — even a simple change to the XML format may require a lot of code hacking. The problem is, of course, we're trying to apply a very linear way of working to a non-linear data structure. If only we could write our event handling code as a tree, so it would mirror the XML.</p> <p>Expert JavaFX Script programmers will be able to guess what's coming next.</p> <pre class="prettyprint"><code>def shopEventTree = Element {<br />    name: "shop"<br />    content: [<br />        Element {<br />            name: "title"<br />            onText: function(ev:Event) { title=ev.text; }<br />        } ,<br />        Element {<br />            name: "customers"<br />            content: [<br />                <span style="color:Blue">Element {<br />                    name: "customer"<br />                    var c:Customer;<br />                    onStart: function(ev:Event) { c=Customer{}; }<br />                    content: [<br />                        Element {<br />                            name: "name"<br />                            onText: function(ev:Event) {; }<br />                        } ,<br />                        Element {<br />                            name: "address"<br />                            onText: function(ev:Event) { c.address=ev.text; }<br />                        }<br />                    ]<br />                    onEnd: function(ev:Event) { insert c into customers; }<br />                }</span><br />            ]<br />        } ,<br />        Element {<br />            name: "products"<br />            content: [<br />                Element {<br />                    name: "product"<br />                    var p:Product;<br />                    onStart: function(ev:Event) { p=Product{}; }<br />                    content: [<br />                        Element {<br />                            name: "name"<br />                            onText: function(ev:Event) {; }<br />                        } ,<br />                        Element {<br />                            name: "price"<br />                            onText: function(ev:Event) { p.price=ev.text; }<br />                        }<br />                    ]<br />                    onEnd: function(ev:Event) { insert p into products; }<br />                }<br />            ]<br />        }<br />    ]<br />}</code></pre> <code class="prettyprint">Element</code> is the first of two JavaFX classes designed to solve our problems. You can see it in action above, being used to create a tree which mimics the XML document we're loading. Each <code class="prettyprint">Element</code> relates to a markup node in the document, with <code class="prettyprint">name</code> representing the node's tag name. Three event functions (<code class="prettyprint">onStart()</code>, <code class="prettyprint">onText()</code> and <code class="prettyprint">onEnd()</code>) fire on the opening and closing tags, or any loose text inside.</p> <p>Note how we now handle the creation of those <code class="prettyprint">Customer</code> and <code class="prettyprint">Product</code> objects (see the highlighted text in the listing). The object is local to the part of the structure it belongs to: <code class="prettyprint">onStart()</code> creates it, the corresponding <code class="prettyprint">onEnd()</code> stuffs it into the sequence, and in-between the nested <code class="prettyprint">Element</code>s populate it.</p> <pre class="prettyprint"><code>def xeh:XMLEventHandler = XMLEventHandler {<br />    eventTree: shopEventTree;<br />}<br />def parser = PullParser {<br />    documentType: PullParser.XML;<br />    input: (new"{__DIR__}test.xml")).openStream();<br />    onEvent: xeh.handleEvent;<br />}<br />parser.parse();<br />parser.input.close();</code></pre> <p>The <code class="prettyprint">Element</code> class has a companion, <code class="prettyprint">XMLEventHandler</code>, which accepts the <code class="prettyprint">Element</code> tree and provides a function for <code class="prettyprint">PullParser</code> to call with its events. <code class="prettyprint">XMLEventHandler</code> tracks the XML's progress and directs the <i>flat</i> <code class="prettyprint">PullParser</code> event to the related <code class="prettyprint">Element</code> event function in our <i>event tree</i>. <code class="prettyprint">XMLEventHandler</code> can tell the difference between the <code class="prettyprint"><name></code> in <code class="prettyprint"><customer></code> and the <code class="prettyprint"><name></code> in <code class="prettyprint"><product></code>, so we no longer need to worry!</p> <p>The above is only an example, and far from perfect. For large XML documents the <code class="prettyprint">Element</code> tree grows to hundreds of lines — hardly ideal. A more professional solution might demand the breaking down of the XML into several sub-trees, which we could model independently and re-use as necessary. Still, <code class="prettyprint">Element</code> and <code class="prettyprint">XMLEventHandler</code> serve their purpose as a demonstration of the power of thinking <i>declaratively</i>.</p> <p>The beauty of JavaFX Script lies in its ability to shape code around the data structures we work with. By utilising JavaFX Script's declarative syntax we were able to transform a (potentially troublesome) linear event handler into an <i>event tree</i> who's source code mirrored the document being parsed. The result was more readable, flexible, and easier to maintain. So, bottom line: don't just think about code to manipulate your data, start thinking about code which mimics (models) your data... :)</p> <p>[<a href="">Source code</a>] (3k)</p> J2SE Tue, 26 May 2009 18:23:33 +0000 javakiddy 242262 at JavaFX in Style <!-- 1153 | 0 --><img src="/images/people/simon_morris.jpg" border="0", align="left" /><p>One of the most touted parts of the new JavaFX API is the ability to skin UI controls using CSS-like stylesheets. However the current 1.0 release seems to be rather light on skin-aware controls, while documentation and examples seem to be rarer than a woman at a Star Trek convention. (That's my derogatory stereotyping quota used up for this year!)</p> <p>Not that lack of documentation ever stopped anyone, of course!</p> <p>A few days back I was playing about with some code, trying to unlock how the stylesheet support might work. All of a sudden a forum posting by tamerkarakan turning up, containing some hastily written (but insightful)<br /> <a href="">notes</a> — presumably the rewards of his own digging around in the code and trial-and-error testing.</p> <p>I thought I'd work his findings up into a more complete, practical, example. What follows is a step-by-step guide to creating your own style-aware JavaFX control, including an external stylesheet which can transform the look of the component without need for recompilation of the JavaFX Script code.</p> <p><img alt="fx_css.png" src="" width="208" height="134" /></p> <p style="clear:both"><strong>Step one</strong> is to create a new type of control which supports a skin. For this example I thought we'd build something pretty simple, a basic progress bar.</p> <pre class="prettyprint"><code>package skindemo;<br />import javafx.scene.control.Control;<br /><br />public class Progress extends Control<br />{   public var minimum:Number = 0;<br />    public var maximum:Number = 100;<br />    public var value:Number = 50;<br /><br />    init<br />    {   skin = ProgressSkin{};<br />    }<br />}</code></pre> <p>The class extends <code class="prettyprint">javafx.scene.control.Control</code> rather than <code class="prettyprint">javafx.scene.CustomNode</code>, giving us access to an inherited field, <code class="prettyprint">skin</code>. This is where we will plug our scene graph code, which actually draws the control. This class just houses our control's public properties.</p> <p><strong>Step two</strong> is to create the skin itself, giving our control a UI.</p> <pre class="prettyprint"><code>package skintest;<br />import javafx.scene.Group;<br />import javafx.scene.control.Skin;<br />import javafx.scene.input.MouseEvent;<br />import javafx.scene.layout.HBox;<br />import javafx.scene.paint.*;<br />import javafx.scene.shape.Rectangle;<br /><br />public class ProgressSkin extends Skin<br />{   public var boxCount:Integer = 10;<br />    public var boxWidth:Number = 15;<br />    public var boxHeight:Number = 20;<br />    public var boxHGap:Number = 2;<br />    public var unsetHighColor:Color = Color.YELLOW;<br />    public var unsetMidColor:Color = Color.GREEN;<br />    public var unsetLowColor:Color = Color.DARKGREEN;<br />    public var setHighColor:Color = Color.ORANGE;<br />    public var setMidColor:Color = Color.RED;<br />    public var setLowColor:Color =  Color.DARKRED;<br />        <br />    def boxValue:Integer = bind<br />    {   var p:Progress = control as Progress;<br />        var v:Number = (p.value-p.minimum) / <br />            (p.maximum-p.minimum);<br />        (boxCount*v) as Integer;<br />    }    <br />    <br /><br />    init<br />    {   def border:Number = bind boxWidth/10;<br />        def arc:Number = bind boxWidth/2;<br />        def lgUnset:LinearGradient = bind makeLG<br />            (unsetHighColor,unsetMidColor,unsetLowColor);<br />        def lgSet:LinearGradient = bind makeLG<br />            (setHighColor,setMidColor,setLowColor);<br />    <br />        scene = HBox<br />        {   spacing: bind boxHGap;<br />            content: bind for(i in [0..&lt;boxCount])<br />            {   Group<br />                {   content:<br />                    [   Rectangle<br />                        {   width: bind boxWidth;<br />                            height: bind boxHeight;<br />                            arcWidth: bind arc;<br />                            arcHeight: bind arc;<br />                            fill: bind <br />                                if(i&lt;boxValue) setLowColor<br />                                else unsetLowColor;<br />                        } ,<br />                        Rectangle<br />                        {   x: bind border;<br />                            y: bind border;<br />                            width: bind boxWidth-border*2;<br />                            height: bind boxHeight-border*2;<br />                            arcWidth: bind arc;<br />                            arcHeight: bind arc;<br />                            fill: bind <br />                                if(i&lt;boxValue) lgSet<br />                                else lgUnset;                    <br />                        }<br />                    ]<br />                };<br />            }<br />        };<br />    }<br />    <br />    function makeLG(c1:Color,c2:Color,c3:Color) : LinearGradient<br />    {   LinearGradient<br />        {   endX: 0;  endY: 1;<br />            proportional: true;<br />            stops:<br />            [   Stop { offset:0;    color: c2; } ,<br />                Stop { offset:0.25; color: c1; } ,<br />                Stop { offset:0.50; color: c2; } ,<br />                Stop { offset:0.85;    color: c3; } <br />            ];<br />        };        <br />    }<br />}</code></pre> <p>Our skin extends (unsurprisingly) <code class="prettyprint">Skin</code>. This is where our UI code for the Progress control actually lives. We create our scene graph and plug it into the inherited <code class="prettyprint">scene</code> variable. The <code class="prettyprint">public</code> properties at the head of the file will be controllable through a stylesheet, as we'll see shortly.</p> <p><strong>Step three</strong> creates a test application for our new Progress control.</p> <pre class="prettyprint"><code>package skintest;<br />import javafx.animation.*;<br />import javafx.scene.Scene;<br />import javafx.stage.Stage;<br />import javafx.scene.layout.VBox;<br />import javafx.scene.paint.Color;<br /><br />var val:Number = 0;<br />Stage<br />{   scene: Scene<br />    {   content: VBox<br />        {   spacing:10;<br />            translateX: 5;  translateY: 5;<br />            content:<br />            [   Progress<br />                {   minimum: 0;  maximum: 100;<br />                    value: bind val;    <br />                } ,<br />                Progress<br />                {   id: "testId";<br />                    minimum: 0;  maximum: 100;<br />                    value: bind val;    <br />                } ,<br />                Progress<br />                {   styleClass: "testClass";<br />                    minimum: 0;  maximum: 100;<br />                    value: bind val;    <br />                }<br />            ];<br />        };<br />        stylesheets: [ "{__DIR__}../Test.css" ]<br />        fill:  Color.BLACK;<br />        width: 200;  height: 100;    <br />    };<br />    title: "CSS Test";<br />    visible: true;<br />};<br /><br />Timeline<br />{   repeatCount: Timeline.INDEFINITE;<br />    autoReverse: true;<br />    keyFrames:<br />    [   at(0s)   { val =&gt; 0 } ,<br />        at(0.1s) { val =&gt; 0 tween Interpolator.LINEAR } ,<br />        at(0.9s) { val =&gt; 100 tween Interpolator.LINEAR } ,<br />        at(1s)   { val =&gt; 100 }<br />    ];<br />}.play();</code></pre> <p>Here we create three instances of our control. The second instance has a specific id, and the third has been assigned a style class. The first has neither. The significance of this will be apparent when we look at the stylesheet, next.</p> <p><strong>Step four</strong> is to create a stylesheet.</p> <pre class="prettyprint"><code>"skintest.Progress"<br />{   boxWidth: 15;<br />    boxHGap: 2;<br />    <br />    setHighColor: yellow;<br />    setMidColor: red;<br />    setLowColor: darkred;<br />    <br />    unsetHighColor: cyan;<br />    unsetMidColor: blue;<br />    unsetLowColor: darkblue;<br />}<br /><br />"skintest.Progress"#testId<br />{   boxWidth: 25;<br />    boxHeight: 30;<br />    boxCount: 7;<br />    boxHGap: 1;<br />    <br />    unsetHighColor: white;<br />    unsetMidColor: silver;<br />    unsetLowColor: dimgray;<br />}<br /><br />"skintest.Progress".testClass<br />{   boxWidth: 7;<br />    boxHGap: 2;<br />    boxCount: 20;<br />    <br />    setHighColor: yellow;<br />    setMidColor: limegreen;<br />    setLowColor: darkgreen;<br />}</code></pre> <p>The above is an external stylesheet file, with three example style rules. The first rule will match any instance of the <code class="prettyprint">skintest.Progress</code> control (all of them, in effect); the second rule will match only that Progress control which has the id "testId"; while the third rule matches any Progress control with the style class "testClass".</p> <p>In each case we are able to manipulate the class properties, change its size, the number of boxes, its colours, etc — all without recompiling the JavaFX Script code.</p> <p>The source code for this mini-project is available <a href="">here</a>. Have fun (and don't forget to buy "JavaFX in Action" when it comes out! :)</p> Swing Wed, 31 Dec 2008 20:21:27 +0000 javakiddy 241347 at No Future In Java <!-- 2829 | 12 --><img src="/images/people/simon_morris.jpg" border="0", align="left" /><blockquote><p>A C++ programmer walks into a Usenet newsgroup, "I don't see the point of Java!" he announces.<br/><br /> "It allows your code to work on many different platforms...", replies a local Java programmer.<br/><br /> The C++ programmer is unconvinced, "I can already do that with C++", he blusters.<br/><br /> "...without re-compiling your code for each platform", adds the Java programmer with a smile.<br/><br /> "What?!", shouts the C++ guy, "Why would I <strong>EVER</strong> need to do anything like <strong>THAT</strong>?!?"</p></blockquote> <p>Okay, so as jokes go it's pretty lame, but conversations not unlike the above were ten a penny back when Java first appeared in the mid 1990s. A lot of programmers just didn't get it &mdash; but then, why would they? They had a lot invested in their current tools, and C++ (Fortran, BASIC, whatever) was serving their needs just fine. The newfangled World Wide Web may have been a fun distraction, but it wasn't likely to change the programming landscape, was it..?</p> <p>Roll forward almost a decade and a half, and it's blindingly obvious why the internet needed something more than C++. The software world evolves, but usually in slow baby-step increments. Very occasionally, however, the industry throws up an idea which tempts us with the promise of a giant leap forward, and a clutch of new and unusual tools emerge to explore the possibilities. Not all <i>giant leaps</i> deliver &mdash; let's not forget Java started life aimed at a smart device explosion which failed to materialise (until years later.) A quick name change and a fresh lick of paint later, and Java became the internet focused technology we know and love.</p> <p>Some say we're rapidly approaching another seismic shift in the software world, at least from a desktop perspective. Whether you agree with the idea or not, Cloud Computing and Rich Internet Applications have many excited (guilty!) In anticipation of this brave new world we have the accompanying slew of strange new tools: Silverlight, AIR, and our very own JavaFX, which debuts in <a href="">only a few days</a>. They promise to change forever the way we think about user facing software, yet already seasoned Java programmers (eg. some respondents to <a href="">Fabrizio Giudici's blog</a> a couple of week back) are asking "What?! Why would I <strong>ever</strong> need to do something like <strong>that</strong>?!?"</p> <!-- <div style="float:left; border:thin solid; padding:5px; margin-right:10px; margin-bottom:10px;"> <a href=""> <img alt="ch8_h.jpg" src="" width="323" height="336" /></a><br/> dhfkjsdhfhsd </div> --><!-- <div style="float:left; border:thin solid; padding:5px; margin-right:10px; margin-bottom:10px;"> <a href=""> <img alt="ch8_h.jpg" src="" width="323" height="336" /></a><br/> dhfkjsdhfhsd </div> --><p>As I see it, there are two questions here: Firstly, will Cloud/RIA computing become a significant force on the desktop? Secondly, assuming it does, how can the Java community grab a share of this market?</p> <p>The first one is easy to answer, a quick Gallic shrug and an apathetic "dunno" will suffice. It's the same answer we can confidently give for man made global warming, or whether any of us will have jobs this time next year. Short of <a href="">James Gosling becoming the eleventh Doctor Who</a>, we can never say with confidence how things will turn out for JFX until some time after the market has already decided. Tipping points are never appreciated when they happen, it usually takes a hefty dose of hindsight to uncover why things ended up the way they did. All we can do is guess at a reasonable worst case scenario, and equip ourselves accordingly.</p> <p>Let's put the first question to one side by assuming RIA's <strong>are</strong> the future &mdash; what should the Java community do about them?</p> <p>Giant leaps are often benefit from new languages, do RIAs need one too? The temptation is to defend our current tools against <strong>any</strong> criticism, to pretend not to notice their blind spots, or to claim their deficiencies don't matter. Recall how our comical C++ coder was quick to equate the cross-platform ability of C++'s source code with the platform neutrality of Java's binaries, and was totally blinded to the benefits of <i>Write Once Run Anywhere</i> in a network-centric world.</p> <p>Surely the most pragmatic answer is, "we don't know"? It seems reasonable to assume RIAs <i>may</i> benefit from some sort of <a href="">DSL</a>, although Swing and WebStart may also suffice. It all depends upon whether the informality associated with browser-based user interfaces is a passing fad, or a permanent change in end user tastes. But one thing we can say with certainty: no industry can progress unless someone takes a punt. The only reason we're talking now about "all the screens of your life" (to paraphrase the JavaFX motto) is because Sun took a gamble with Java. (Just how far would we have got with C++ and Perl...?)</p> <p>There are indeed some similarities between the early days of Java and JavaFX: JFX, like Java, will be launched in the face of a well established (and entrenched) opposition, and doesn't truly innovate so much as integrate and focus established but less visible ideas into a tool suited for solving a particular type of problem. But there's also some pretty stark differences too: in 1995 Java could ride on the guaranteed <i>street cred</i> of bringing eye candy colour to otherwise grey HTML pages, yet in 2008 JavaFX doesn't have the market to itself, and rippling lake applets no longer wow today's fickle users.</p> <p>JavaFX's big trump card is it's interoperability with Java. Rather than the client/server chasm inevitable with rival technologies &mdash; Java on the server, ActionScript on the client, for example &mdash; the developer can decide how far across the span of the application Java should reach. It's possible to develop a thin JavaFX Script veneer over heavyweight Java libraries, or (the other extreme) to restrict Java to only a server side role and let JFX rule the desktop &mdash; the option is left open. This causes familiar chasm-straddling technologies (SOAP/JSON/REST/etc,etc,etc) to be demoted to implementation choice instead of mandatory requirement.</p> <p>Only time will tell what the future has in store for JavaFX. If it turns out RIAs don't deserve a whole new platform, and Java will suffice, then we haven't lost much in hedging our bets. If the opposite is true, however, then at least JavaFX still gives us a fighting chance...</p> Swing Wed, 26 Nov 2008 23:39:32 +0000 javakiddy 241208 at Shocking Ideas: Coding Should Actually Be Fun!! <!-- | 0 --><p>If you're following my recent adventures (do you have nothing better to do?) you'll know I've been spending a lot of time with JavaFX Script recently. It's a language which targets a wider audience than its bigger cousin &mdash; more Javascript than Java. Thanks to <a href="">The Java Posse</a> I was recently alerted to Fabrizio Giudici's <a href="">blog</a> asking which scripting languages should be supported in his blueMarine project. And then there's our illustrious editor's own <a href="">blog</a> of a few days back, in which he concludes:</p> <blockquote><p>High-school age programmers probably don't want to write financial applications or transactional databases... but they might be interested in making devices see, hear, spin, roll, lift, and/or just blow up. Can they use Java for that? Should they?</p></blockquote> <p>All three of these, in their own way, address a common issue: how do we bring the complex world of software development within the reach of the novice (or occasional) programmer?Okay, time for another "when I was a lad" digression: in days of yore to know about "computers" was to know about programming. Mainly BASIC, which was the language of choice on early home computers. Amazing as it seems, the computer actually "booted" straight into BASIC, and general housekeeping tasks like loading a program or deleting a file were done through BASIC direct mode instructions. The core of every high school "Computing" course (the ugly term "I.T." had yet to be invented) was coding software. Sure, you'd be shown a <i>word processor</i>, on the off chance you might encounter such an exotic beast in the outside world (and if you were really lucky you might have ten minutes on a spreadsheet) but mainly it was programming, programming, programming.</p> <p>How times change!</p> <p>Not that I'm complaining, things can't stand still, and the BASIC front-end was doomed to be replaced almost from the moment it first appeared. And naturally this would be reflected in the classroom. But I sometimes wonder if removing <strong>all</strong> programming from the core I.T. curriculum, and parcelling it off into speciality modules, was a wise decision. Increasingly the rich multimedia world we live in is exposing itself to the end user by way of programming APIs and software languages. At one end of the scale we have HTML: although not strictly a programming language it <strong>is</strong> a form of 'coding', which benefits from a familiarity with software development. At the other end of the scale we have an increased visibility (and importance?) of <i>script-ability</i> features, like those Fabrizio is considering for blueMarine.</p> <p>JavaFX Script is a domain specific language for graphics, in itself not an idea which one would consider controversial. But the decision to make the syntax akin to scripting languages like ECMAScript did appear to raise a few eyebrows when JavaFX was first formally taken into the Java family a couple of Java One's back. Is this a case of some of the Java faithful adopting a rather snobbish attitude to a syntax clearly designed to court the likes of web designers and animators(..?) (An aside: I urge anyone with mixed feelings to give JavaFX a second try when the full release arrives shortly &mdash; there's a lot of power hidden beneath that user-friendly facade.)</p> <p>If I'd have been born ten or fifteen years after I was, I probably wouldn't have become a programmer! Without an interest in financial applications or transactional databases (strange that!) I would presumably have given software development a miss. As Chris Adamson so succinctly noted, the mainstream languages like Java don't seem to offer much that would fire the imagination of young programmers. Even platforms like Flash and phone MIDlets, once awash with games, now seem more concerned with boring middle-aged pursuits like database connectivity and web services.</p> <p>What I see is a world in which every part of our lives &mdash; no longer just our work, but our play too &mdash; is being moved into the digital realm. Our music, our memories, our innermost secrets, increasingly they are being digitised and pushed onto the cloud (whether or not that's a good idea is an entirely separate debate!) Anyone with at least modest levels of coding skill is at an advantage in making these tools work and inter-operate. Yet the routes into programming seem dry and stuffy, devoid of any fun or instant gratification &mdash; a far cry from twenty years ago.</p> <p>Technologies like JavaFX, with rapid code/compile/test cycles (for near instant gratification) and accessible multimedia features may offer the answer. But do they risk being tainted by unwarranted criticism from hard-core coders who see their average-Joe syntax, and just don't 'get it'?</p> Programming Fri, 31 Oct 2008 00:41:07 +0000 javakiddy 241081 at JavaFX Script: the 100 Line Challenge <!-- 3280 | 0 --><img src="/images/people/simon_morris.jpg" border="0", align="left" /><p>There must be a name for that particular form of programming masochism which involves wringing the maximum effect out of the minimum of code. If not, someone should invent one!</p> <p>I first began coding when the Apple II and Commodore 64 (et al...) opened up computing to the masses. By modern standards their 32 or 64k of RAM is an impossibly small amount &mdash; I'd love to report it was more than enough back in the day, but I'm reminded of all those evenings I spent <i>byte shaving</i>. Still, as frustrating as it could sometimes be, there was a certain joy in coding those older systems, a certain pride in making everything as tight as possible to fit the most in. Shaving every byte, stripping away redundant clock cycles (<a href="">zero page addressing</a>, anyone?) and banking the Kernal ROM (Commodore's spelling) in and out of the <a href="">6510</a>'s address space to get at the RAM 'underneath'.</p> <p>In this age of the gigabyte, it can still be a useful exercise to see how much one can do with a given technology under tight (if artificial) constraints. The legendary <a href="">64k intro</a> scene is a modern example, but as long ago as the 16 bit days I seem to recall a <a href="">STOS</a> or <a href="">AMOS</a> BASIC sponsored competition for writing games in ridiculously few lines of code (ten..?) (Actually, wasn't <a href="">Brainf**k</a> the product of an Amiga owner?)</p> <p>In recent weeks I've found myself <a href="">needing to develop</a> a lot of small JavaFX examples. I looked at what Joshua Marinacci had done with <a href="">his 45 line 'preview' demo</a>, setting the bar quite high, and wondered if I could do better...The increase in power of our computers has necessitated layers of abstraction. By contrast the graphics on the old 'micros' involved nothing more than writing values into the right place in RAM. Of course graphics were very much more primitive in the 8 bit days, but for instant coding gratification I have to confess nothing has ever really beaten the thrill of poke-n-play. Which is why domain specific technologies like JavaFX come as such a welcome change &mdash; not that they allow old fashioned <i>bash the metal</i> coding, but they certainly put some of the immediacy back into graphics work.</p> <p>After experimenting with JavaFX Script for a while I came up with the following self-imposed rules, seemingly offering a suitable balance between challenge and frustration:</p> <ol> <li><i>One source code file.</i></li> <li><i>One hundred or fewer lines of code.</i></li> <li><i>No external data files.</i> It's too easy to cheat with animated images and the like.</li> <li><i>Eighty columns maximum.</i> No ridiculously long lines of code.</li> <li><i>Modestly readable source.</i> Obviously there's a temptation to optimise the amount of code on each line, and ignore comments, but the source should still be indented and laid out in a <i>fairly</i> readable way.</li> </ol> <p><img alt="Bouncing Balls" src="" width="380" height="295" /></p> <p>The bouncing balls was my opening gambit, which admittedly was a bit hit and miss. There's various effects on show here: the balls bouncing on a reflective surface, colour transitions as the mouse enters of leaves the scene, and faux lighting which shifts across the balls and background as the mouse pointer moves. To be honest, I think its a bit of a dog's dinner of effects and tweens.</p> <p><img alt="Fireworks" src="" width="443" height="353" /></p> <p>My second attempt was a bit more focused: a fireworks effect. At random intervals multi-coloured rockets shoot into the night's sky, before exploding with a flash into sparks, drifting back towards the ground and fading as they go. It's a pleasing enough effect, but I get the feeling there's still more which can be done. I'm thinking perhaps something faux 3D, or involving parallax scrolling?</p> <p>As you may be able to tell, it's quite addictive stuff. With only 100 lines to play with the mind races, searching for cunning ways to create big effects with small amounts of code. I can certainly see why the 64k guys do it.</p> <p>If you want to check out the demos for yourself the source code (all 193 lines, combined) is available <a href="">here</a>. It should build/run using the 1st Preview of JavaFX from a few weeks back, with Java 6 update 10.</p> <p>And so, I hereby throw down the gauntlet to anyone who can come up with even cooler demos (or improve the two above.) Do you think you can beat my fireworks, in 100 lines or less? Surely it can't be too hard?!? Go on, give it a try &mdash; like me, you may be surprised at just how much fun it is!</p> Swing Tue, 30 Sep 2008 19:29:00 +0000 javakiddy 240945 at Watched Pots and JavaFX <!-- | 0 --><p>In <a href="">recent weeks</a> I've been immersed in the strange and exciting world of the JavaFX Preview release. Some might say up to my neck, although sometimes it's felt more like drowning. JavaFX makes a lot of previously very complex graphics tasks now very simple. At the same time it makes a lot of previously very simple tasks now frustratingly hard!</p> <p>Of course, this is merely preview release one &mdash; another update is apparently scheduled for this November, so perhaps some headaches will be addressed by then. Here's hoping! But for now here's some random gripes, observations (and a little bit of interesting source code) relating to the current release.One of the main problems of developing using the recent preview release is the mass of outdated documentation, tutorials, and other such matter floating around on the Internet. JavaFX has been through a lot of changes and redesigns, with the current preview release being very different in both API and language syntax to the original F3-inspired platform which made its debut eighteen months ago at JavaOne 2007. When searching for any JavaFX related query one has to remember to always check the date when the resulting pages were posted, as pages relating to the old JFX seem to far outnumber the new.</p> <p>While it's perfectly understandable that the various commentaries and examples scattered across the far flung corners of the internet are still available, some of the obsolete documentation seems to be hosted by Sun itself! [<a href="">1</a>][<a href="">2</a>] Surely they can spare a few moments to take it down, update it, or at least flag it as outdated?</p> <p>Coding in JavaFX is really quite an enjoyable experience compared to hacking away at Swing. The declarative syntax is a real boon for getting stuff on screen quickly, and the timeline system takes all the pain out of getting things to animate. Perhaps this is why problems, when they <strong>do</strong> rear their ugly head, seem all the more acute?</p> <p>Event handling was one example. JavaFX Script supports function types (variables which reference functions), and uses them for event handling. This means only one handler can be assigned to each event type. A clickable node (a button) might want to act on its own mouse clicks, for the purposes of animation, but also allow external classes to receive the click events too. The solution might be to create another event type, "action" for example, and republish the mouse click to the outside world as an <i>action</i> event. But if a subclass of the button then needs to know when action is fired, presumably <strong>yet another</strong> event type is needed to republish the action event(?)</p> <p>I wondered whether I could chain event handlers, but this proved unworkable from within the declarative syntax. And besides, even if I'd gotten it to work, it would have been a clumsy solution. Some sort of event multiplexing would be useful, although quite how that would work I don't know. Sure, each event function type could become a sequence (array), but how does one append a function to said sequence declaratively?</p> <p>It's not the end of the World &mdash; we can survive without an event mux! But can we survive without layout managers?</p> <p>The scene graph model seems to be orientated more towards nodes having control over their own position and dimensions. Certainly many drawing primitives (circle, rectangle, image) permit some control, but the top level <code>Node</code> class, and containers like <code>Group</code>, do not. You can find out how big they are, but (short of scaling or clipping) can't request a particular size. At the moment only a couple of very basic layout classes are included; one look at their source exposes plenty of hooks into undocumented low-level mechanics from their <code>Group</code>/<code>Node</code> parents.</p> <pre>package jfxgui.layout;<br/><br/>import javafx.scene.Group;<br/><br/>public class GridBox extends Group<br/>{ public attribute columns:Integer=1<br/> on replace { impl_requestLayout(); }<br/> <br/> init<br/> { impl_layout = doBoxLayout;<br/> }<br/> <br/> private function doBoxLayout(g:Group) : Void<br/> { var maxWidth:Number=0.0;<br/> var maxHeight:Number=0.0;<br/> <br/> for(n in content)<br/> { maxWidth = if(n.getBoundsWidth() > maxWidth) <br/> n.getBoundsWidth() else maxWidth;<br/> maxHeight = if(n.getBoundsHeight() > maxHeight)<br/> n.getBoundsHeight() else maxHeight;<br/> }<br/> <br/> var i:Integer=0;<br/> for(n in content)<br/> { var x = i mod columns;<br/> var y = (i / columns).intValue();<br/> n.impl_layoutX = x*maxWidth;<br/> n.impl_layoutY = y*maxHeight;<br/> i++;<br/> }<br/> }<br/>}</pre><p> The GridBox class above uses the same techniques as the scene graph's existing layout classes to reproduce AWT's <code>GridLayout</code>. You can see all the references to the undocumented <code>impl_</code> attributes and functions, required to control content layout. The AWT <code>GridLayout</code> sizes its contents to identical dimensions, but I'm not aware of a safe/recommended way to do this with <code>Node</code>s.</p> <p>So is JavaFX a waste of space? Absolutely not! Don't get me wrong, JavaFX is a great technology, and JavaFX Script is shaping up nicely as a really cool <a href="">DSL</a> for graphics and effects programming. It's precisely because it gives you such a feeling of liberation that the problems, when encountered, stand out even more.</p> <p>I've no doubt future releases of JFX will address much of the above, but with only a few months to go before the version 1.0 release, I just wonder how much of that (crucial, opinion forming) first release will be marked "coming soon"?</p> Web Applications Thu, 28 Aug 2008 20:54:51 +0000 javakiddy 240774 at When Buzzwords Go Bad <!-- | 0 --><p>I always assumed the word "jargon" was a reasonably recent addition to the English languages, but a quick glance at the <a href="">OED</a> gives examples of its use dating back as far as Chaucer. It would seem that man has been uttering "<i>... unintelligible or meaningless talk or writing; nonsense, gibberish</i>" for centuries! Or perhaps that should be "<i>...conversing by means of symbols otherwise meaningless; a cipher, or other system of characters or signs having an arbitrary meaning</i>" ? </p> <p>Gibberish, or just a cipher? The dual meaning perhaps reflects the inclusive/exclusive nature of <i>jargon</i> &mdash; if you're part of the 'in group' jargon is useful shorthand, but to outsiders that same jargon is unintelligible and meaningless.</p> <p>If "jargon" is centuries old, I wonder how old is the practice of using it to confuse and bedazzle? The OED's earliest source for "management speak" ("[...]being obfuscatory, needlessly complex, or empty of useful meaning.") only dates back to a 1986 Sunday Times article, yet I suspect the practice is far far older.</p> <p>The problem is no sooner has a new term entered the lexicon than someone, somewhere, will start to abuse it for whatever reason. The unfortunate popularisation of term "web" in place of "internet" was likely due to the ignorance of many politicians, journalists and other commentators during the early years of the fledling technology. However, years later the wholesale abuse of the (far too sexy for its own good) phrase "Web 2.0" was more down to 'marketing' than anything else.</p> <p>This is precisely what has happened to "RIA", Rich Internet Application, a piece of jargon now so diluted through multiple interpretation that it doesn't really mean <i>anything</i> any more &mdash; at least, so say the members of the <a href="">Java Posse</a> in their 24th July podcast.</p> <p>Is RIA meaningless? And if so, is it worth replacing it with a new term?<br /> <h2>Really Indeterminate Acronym</h2> <p>First let us take apart the existing term: RIA &mdash; Rich Internet Application. What does it mean?</p> <p><strong>Attempt #1:</strong> "Any application dependant upon the internet for its function."</p> <p>Seems reasonable enough at first sight. By this measure Google Earth would make it onto the list because of its need to constantly draw data across the network, and iTunes would also make it because its catalogue is online. But hold on, what about Firefox? What about Internet Explorer? Windows Update? FTP? Telnet? All of these depend largely upon the internet for their operation.</p> <p>Okay, scratch that, it's clearly far too broad.</p> <p><strong>Attempt #2:</strong> "Any application which runs inside a web browser."</p> <p>This one surely has to be a winner! After all, we all know GMail is an RIA, right?!?</p> <p>So Google Search is an RIA too. And <a href="ttp://;">that Swedish Chef</a> translator which was all the rage ten years ago. Hmm, somehow that just doesn't seem right. Pretty much any non-static web page would be an RIA by that token.</p> <p><strong>Attempt #3:</strong> "Any application which runs inside a web browser and looks cool!"</p> <p>So <i>coolness</i> of user interface is the benchmark by which we judge whether a web site is an RIA or not? But what if we use Java applets, or Flash, do they count? We'll soon be able to drag and drop an applet out of the browser window and onto the desktop, where it will run independent of the browser &mdash; is it still an RIA?</p> <p><strong>Attempt #4:</strong> "Any application which runs <b>inside</b> a web browser page, not outside a browser page (even if it started life inside a page!) and looks cool!"</p> <p>Aha, fine. But my Java applet (which is still on the page) opens a top-level Swing window on the desktop, complete with "<i>this is an applet</i>" warning banner.</p> <p><strong>Attempt #5:</strong> "Any application which runs <b>inside</b> a web browser page, not outside a browser page (even if it started life inside a page!), or at least has 'one foot' still 'planted' on a browser page, even if it opens other windows... and looks cool!"</p> <h2>Right, I Acquiesce!!</h2> <p>My own personal definition is this: "Any application which has the sophistication of a desktop application, but the omnipresence of a web site".</p> <p>I've focused on the word "internet" as being where the application lives, rather than what it does. So an images manipulation tool, which allows me to work on an image on my local hard disk (rather than on Flickr or wherever) would still be considered an RIA if it was accessible via a URL. The criteria are: the UI has the feel and finesse of a desktop application (rich), the application needs no formal installation &mdash; although it may be cached (internet), and it's software not data (application).</p> <p>Under this definition GMail is in, and so are applet and Flash applications regardless of whether they live inside a browser page. WebStart applications are also included. But Google Search is out (not rich) and so is Google Earth (requires installation).</p> <p>The problem is the odds of anyone else agreeing with the above are less than <a href="">Google bringing out a JavaFX version of GMail</a>.</p> <p>The Java Posse suggested the term RIA be retired in favour of something new. Perhaps they are right! Much of the confusion seems to surround distinguishing browser RIAs from their virtual machine counterparts, and as the web has far more of the <i>mind share</i> I suspect it is beholden to the VM community to make the first move. The Posse suggested various acronyms like IRIS or IRA as replacements, although I suspect the latter might not go down too well in some parts of Ireland! (I considered a joke about coding wearing a balaclava at this point, but too many angry Irishmen know where I live!)</p> <p>Mulling it over, the best I could come up with was "RADICAL apps": Rich Animated Desktop Interface / Cloud Abstraction Layer. Not the best acronym in the World, but it encompasses the key concepts: <i>Rich Animated Desktop Interface</i> (slick UI, but not in a browser!), <i>Cloud Abstraction Layer</i> (not installed, lives and works through network 'abstractions' like URIs and Web Services.)</p> <p>Of course, all we're really doing is creating <strong>another</strong> buzzword, ripe for abuse and misuse. And this is the fundamental dilemma at the heart of naming any new concept (as opposed to something concrete, like a product or a web site) &mdash; the sexier the name the more it sticks in the imagination. The 'stickier' it is, however, the more likely it is to be mutated.</p> <p>Even so, I think it might be good to have a sexy new term for VM based RIA's, if only to placate my curiosity as to how long it will take before references to "RADICAL applications" (or whatever) in conjunction with "GMail" start to materialise on Google! ;)</p> Web Applications Thu, 31 Jul 2008 22:25:12 +0000 javakiddy 240622 at Flogging a Dead Horse <!-- | 0 --><p>Today is apparently Bill Gates' first day away from Microsoft. As he leaves, some have suggested Microsoft's star is now in the descent, as Google's star climbs ever higher. Is this really the case, is Google destined to become the next Microsoft? When a company attains a certain dominance in the market, isn't it hard to unseat them? After all, they can afford to hire all the best people!</p> <p>Cast your mind back to IBM's nervous toe-dipping when it came to the fledgling micro computer market in the Seventies, or Microsoft's initial head-in-the-sand attitude towards the internet in the Nineties &mdash; being big doesn't always make you right. Indeed the larger the organisation, the better it gets at sustaining incorrect assumptions in the face of mounting contradictory evidence. (One wonders, for example, whether a concept like <a href="">transubstantiation </a> could ever have survived in a religion with only a handful of members?)</p> <p>There's safety in numbers, for sure, but only by way of passing the buck for a bad idea. Shared responsibility can often mean no responsibility at all. In the right environment bad <a href="">memes</a> can survive unchallenged, and humans seem particularly good at creating those environments. We believe because the people around us believe, not because we have given an idea careful contemplation or scrutiny. What's important is that the group has clear goals; how well those goals stand up to reality is of secondary concern. As the song says: "any dream will do!"Google prides itself on hiring only the select few, the brightest of the bright. But a youthful company with an allegedly youthful workforce, all recruited from similar stock, doesn't leave much room for diversity of outlook. Those familiar with tale of Apple Computer's first decade will know how a group of supposedly intelligent people can divorce themselves from reality when they're distracted by working on new and exciting technologies.</p> <p>With so many developers recruited straight out of university, one wonders how many Google engineers really remember programming before the arrival of web? Perhaps unsurprisingly Google is wedded to the web as a platform for Rich Internet Application development, yet is there any strong evidence that this is a fruitful avenue to pursue?</p> <p>Sure, Gmail is used by many, but what of Google's other web-app offerings? Docs? Spreadsheet? Does anyone, aside from the occasional curious soul, seriously use these applications? I don't think so! Yet Google continues to develop and promote the likes of GWT (Google Web Toolkit) and Gears, technologies designed to smooth over or work around the obvious shortcomings in the web platform.</p> <p>If I was being cruel I might wonder whether the true genius of Google lies in finding more inventive ways to flog a dead horse! When you consider the promise of Adobe's AIR, Microsoft's Silverlight, or indeed Java's own JFX, you wonder why we aren't seeing evidence of significant investment in these technologies &mdash; or at the very least in one of them. Silverlight and JavaFX may still be raw, but AIR is mature enough to start producing applications, if only exploratory beta releases.</p> <p>Perhaps behind the scenes there are indeed moves to examine these alternative RIA technologies? Maybe, as I write, the latest build of a JFX based Google Docs has just finished compiling, or an Adobe AIR Gmail has been handed off for internal testing...? But there's very little evidence of that from the <a href="">itinerary</a> of the recent Google I/O conference.</p> <p>The problem with these non-web RIA platforms is they rely on a foundation of software already being installed on the user's desktop &mdash; in the case of JavaFX, for example, it's the JRE. Having to stop and install a plugin creates a hiccup in the user experience; by contrast the web browser is guaranteed to be present. So the future of non-web RIAs depends upon breaking an old chicken/egg scenario: RIAs won't start being written until runtimes are ubiquitous, and runtimes won't be ubiquitous until there's enough RIAs to drive demand for them.</p> <p>Microsoft has the option of simply pushing Silverlight out like it did with IE 7, such are the perks of owning the OS which runs on 90% or so of the World's computers. While the roll out wouldn't reach every Windows user, it would cover enough to make Silverlight a lot more attractive. Can Google afford to wait for Microsoft to do this?</p> <p>The only vendor of RIAs which has the clout (in terms of brand recognition and trust) with the common user is Google. If Google announced an enhanced Adobe AIR version of Gmail you can bet your bottom dollar it would generate plenty of headlines. Yet Google seems content to keep prodding the web, in the hopes it will somehow transform itself, in the best Cinderella fashion, into an effective RIA vehicle.</p> <p>There's plenty of paranoia about Google around at the moment. People are whispering "the next Microsoft" every time Mountain View announces a new product. Yet I wonder if, by shackling themselves only to the web and not dabbling with these other technologies, Google hasn't committed itself to something it will later regret?</p> <p>Of course Google could be right &mdash; maybe the future of the RIA <strong>is</strong> inside the browser. And even if they're wrong, there's still plenty of time to do a U-turn (although by waiting they could forfeit the opportunity to champion their preferred platform.)</p> <p>For the sake of us all, I sincerely hope they <strong>are</strong> wrong, and they'll start dabbling with JavaFX or AIR sooner rather than later!</p> Web Applications Mon, 30 Jun 2008 22:57:00 +0000 javakiddy 240479 at