Geertjan is a DZone Zone Leader and has posted 466 posts at DZone. You can read more from them at their website. View Full User Profile

How Groovy Helps JavaFX: Farewell Pure Java Code?

  • submit to reddit

One of the many cool sample applications known to those trying out JavaFX is the JavaFX Weather application, which is now bundled with the NetBeans IDE 6.5.1/JavaFX 1.2 bundle. In short, it connects to a weather service and then displays the results for selected cities in an impressive JavaFX GUI:

In a technical session at JavaOne on Wednesday, entitled "JavaFX Programming Language + Groovy = Beauty + Productivity", Dierk König showed a number of powerful ways in which Groovy and JavaFX can interact. One of those ways is outlined below, with all the code and the results. It is really quite impressive and earned Dierk a round of applause from his audience when he demoed it in his session.

The JavaFX Weather application creates the above GUI, while using this massive Java class to connect to Yahoo's weather service. The RSS feed that the Java class connects to is displayed in full below:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="" xmlns:geo="">


        <title>Yahoo! Weather - Prague, EZ</title>
        <description>Yahoo! Weather for Prague, EZ</description>
        <lastBuildDate>Fri, 05 Jun 2009 8:00 pm CEST</lastBuildDate>

        <yweather:location city="Prague" region=""   country="EZ"/>
        <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
        <yweather:wind chill="54"   direction="60"   speed="3" />
        <yweather:atmosphere humidity="58"  visibility="6.21"  pressure="29.8"  rising="0" />
        <yweather:astronomy sunrise="4:56 am"   sunset="9:06 pm"/>

            <title>Yahoo! Weather</title>


            <title>Conditions for Prague, EZ at 8:00 pm CEST</title>
            <pubDate>Fri, 05 Jun 2009 8:00 pm CEST</pubDate>
            <yweather:condition  text="Partly Cloudy"  code="30"  temp="54"  date="Fri, 05 Jun 2009 8:00 pm CEST" />
<img src=""/>
<b>Current Conditions:</b>
Partly Cloudy, 54 F
Fri - Partly Cloudy. High: 58 Low: 42
Sat - PM Rain. High: 58 Low: 49
<a href="*">Full Forecast at Yahoo! Weather</a>(provided by The Weather Channel)<br/>
            <yweather:forecast day="Fri" date="5 Jun 2009" low="42" high="58" text="Partly Cloudy" code="29" />
            <yweather:forecast day="Sat" date="6 Jun 2009" low="49" high="58" text="PM Rain" code="12" />
            <guid isPermaLink="false">EZXX0012_2009_06_05_20_00_CEST</guid>




Now, whenever you hear "Groovy", you should think "grunt work". That's what Groovy is particularly good at. A very strong case in point is that of web services. Also, that of parsing HTML and XML. Therefore, when you need to interact with web services in your Java application, the most obvious helper language you should think of is Groovy.

Look again at the RSS above and then look at line 11 in the Groovy code below. Here's that line:

def channel = new XmlParser().parse(url).channel
That line gets you the "channel" element in the RSS feed above! Awesome, right? And from there on, the Groovy script below parses the RSS feed, identifying exactly those pieces that are of interest to the JavaFX GUI, resulting in EXACTLY the same result, in approximately 20 lines, as the original does in approximately 250.

Take a look at the Groovy snippet below to see how it works, by comparing it to the RSS feed above. Note that this isn't even a snippet! It is the WHOLE Groovy web service class. Now that's just plain cool, especially after comparing it again to the original monstrosity.

package weatherfx.service

class YahooWeatherServiceG {
static YW = new groovy.xml.Namespace("")

def forecasts

YahooWeatherServiceG(String code, boolean celsius) {
def url = "$code"
println url.toURL().text
def channel = new XmlParser().parse(url).channel
cityName = channel[YW.location].@city
def wind = channel[YW.wind].first()
windSpeed = wind.@speed.toInteger()
windDirection = wind.@direction.toInteger()
def cond = channel.item[YW.condition].first()
temp = cond.@temp.toInteger()
forecasts = channel.item[YW.forecast]

String cityName
int temp
int windSpeed
int windDirection

int getConditionCode(int day=0) { forecasts[day].@code.toInteger() }
int getLowsTemp (int day=0) { forecasts[day].@low.toInteger() }
int getHighsTemp (int day=0) { forecasts[day].@high.toInteger() }

Now, take a moment to imagine how much simpler, effective, and less error-prone it will be to (a) test and (b) maintain the above code, compared to its original pure Java version.

However, there isn't a JavaFX/Groovy cross-compiler yet. So, how to replace your Java web service code with the above in Groovy? Create a separate project in which you create your Groovy web service. Then add that project to your JavaFX application's classpath. Next, replace the two or three references in your JavaFX application to refer to the Groovy class (which, after compilation, is now a Java class) instead of the original Java class.

In a single picture, the above paragraph gets you the following:

Then run the JavaFX application and you'll have the same result as before, with the difference that the web service code is now handled in Groovy. And... there's no pure Java code in your application at all anymore. Oh, dear. JavaFX creates the GUI, while Groovy does the grunt work in the background. So, farewell, pure Java code?


fig-1.png46.71 KB
YahooWeatherService.java9.45 KB
fig-2.png68.64 KB
Published at DZone with permission of its author, Geertjan Wielenga.


Otengi Miloskov replied on Sun, 2009/06/07 - 8:55pm

I like groovy but we still need to use Java. The performance and memory consumption of Groovy compared with Java is laughable. We will see but I will replace better Java with Scala than Groovy also static typing with functional have a lot of advantages thanks also to type inference.

Cloves Almeida replied on Sun, 2009/06/07 - 9:45pm

I believe performance will be a non-issue, the VM is getting "smarter" about dynamic languages. I sometimes use groovy and *really* like it, howerver I can't get used to dynamic typing. The time I save typing get blown by bugs the compiler would catch otherwise. That's why I second to Scala, once it gets more tooling and vendor support.

Andrew replied on Sun, 2009/06/07 - 10:26pm

Hmmm, Is not it overcomplicated to use 3 languages for such a simple widget?

Dean Del Ponte replied on Sun, 2009/06/07 - 10:26pm

Groovy performs well enough for most applications (as do Ruby and PHP) and where your Groovy code isn't fast enough, you can write Java code. The integration between the two is seamless. Also, if you don't like dynamic typing, then use static typing. Nothing is stopping you from using static typing in Groovy. That's one of great things about it. If you're concerned about being bitten by bugs because you're using a dynamic language, I recommend unit testing and a good continuous integration server.

James Jamesson replied on Sun, 2009/06/07 - 11:40pm

The posts which favor abondoning Java has been steadly increasing in Javalobby. Why? I can understand Sun's ambition to force JavaFX to the mainstream, but It wont fly this way. I am here to read Java related news and technologies and certainly not well crafted non-java corporate propaganda. From the way it goes, I probably wont be reading Javalobby from this fall on. I wont use JavaFX because I do not need it, and like JavaScript, JavaFX aint Java. You should create a JavaFX Zone for those who are interested and stop polluting my feed with non-Java stuff.

Andres Almiray replied on Sun, 2009/06/07 - 11:57pm in response to: James Jamesson

That depends on your definition of "Java": is it the language or the platform? or both. Frankly I don't care if a JavaFX (or any other alternate JVM language for that matter) post appears from time to time on my Javalobby feed, I can decide to skip it if I want to. Disclaimer: I love Groovy, I don't like JavaFX Script that much, I'm partial to Scala and I'm a total ignorant on Clojure. Tag me as a madman, I prefer polyglot programmer ;-)


Andrew replied on Sun, 2009/06/07 - 11:58pm in response to: James Jamesson

JavaFX aint Java! Thanks jamesjames this is exactly my feeling. This article is posted on Groovy zone and it should not be cross posted on Java zone because it has nothing to do with Java. Its about a time to make JavaFX zone and move all this JavaFX noise from Java zone there.

Geertjan Wielenga replied on Mon, 2009/06/08 - 12:45am in response to: James Jamesson

"non-java corporate propaganda"? Read the article again... it is not about JavaFX, but about Groovy. If this were "non-java corporate propaganda", I would be working for SpringSource, I guess. You better get me Rod Johnson's e-mail address so I can ask him for my paycheck.

James Jamesson replied on Mon, 2009/06/08 - 1:01am in response to: Geertjan Wielenga

I had to read the title of your article to skip the rest, and I am not sorry for that. I am here to read Java related news. On the other hand, I do not know what you do or who you work for, and frankly, I would not care. I made a general statement because it is clear to me that "JavaFX" is used with Java in every possible occasion to push its non-Java existance. And, unfortunately, Java itself is used to promote a scripting language which for some reason cryptically has a Java word in its name. Those tricky marketing tactics, It should have been called something else.

Michal Hlavac replied on Mon, 2009/06/08 - 1:11am in response to: James Jamesson

jamesjames, Andrew
It's interesting, how intolerant readers are here. This article is strongly about java. Why didn't you simply skip this article? (rhetorical question)

James Jamesson replied on Mon, 2009/06/08 - 1:18am in response to: Michal Hlavac

Well, if the title of the article were tolerant towards Java, I would have gladly ignored it. It just does not read right. It is almost like asking to favor JavaFX over Java in there somewhere. It is not a perfect world, some of us are not very tolerant enough I guess. Why would that bother you? should it have to be always with roses and flovers? just a rhetorical question ;).

Andrew replied on Mon, 2009/06/08 - 1:37am in response to: Michal Hlavac

Why you call me intolerant? For articles about Groovy there is Groovy zone and the author posted his article there. I think for JavaFX stuff there should be JavaFX zone. That’s it.

Michal Hlavac replied on Mon, 2009/06/08 - 1:59am in response to: Andrew

these words were primary for jamesjames, because as we know he likes javascript and doesn't like javafx. there are lot of dzone readers who like javafx and don't like javascript. May be somebody should create JavaFX Zone, but I think this step doesn't solve "problem". Lot of dzone articles are about more than one technology. It's impossible to create article using only technologies who like everybody. And this is about tolerance.

James Jamesson replied on Mon, 2009/06/08 - 2:50am in response to: Michal Hlavac

"we know he likes javascript and doesn't like javafx" huh? Where did you get the idea that I like Javascript? and how would you know what I like. I said I would not use it. I didnt say anything about not liking it. who are you, agent X?

Michal Hlavac replied on Mon, 2009/06/08 - 2:51am in response to: James Jamesson

Come on james, you really missed point. No offence, please...

Geertjan Wielenga replied on Mon, 2009/06/08 - 2:56am in response to: James Jamesson

It is almost like asking to favor JavaFX over Java in there somewhere.


Hmmm. Not in one single place has that argument been made in this article. Not even once. If anything, it's asking you to favor Groovy over Java.

James Jamesson replied on Mon, 2009/06/08 - 3:03am in response to: Michal Hlavac

Come on what? you are claiming things about me. I really didnt like that. Again! Where did you get the idea that I like Javascript(huh!) and dislike JavaFX. I made a decent point on a bothersome JavaFX campaing which is built on top of Java's popularity. Do you have any arguments on that?

Andrew replied on Mon, 2009/06/08 - 3:04am in response to: Michal Hlavac

Hi Michal,

I agree with you that when you wrote an article about several technologies it is difficult not to rush to publish it on any board possible.

However, I share some concerns with jamesjames that JavaLobby board is being used for preaching JavaFX / Groovy over Java.

Just look at the title "… Farewell Pure Java Code?".

And further the author writes

Quote 1:
"Now that's just plain cool (Groovy), especially after comparing it again to the original monstrosity (Java)."

Quote 2:
"Now, take a moment to imagine how much simpler, effective, and less error-prone it will be to (a) test and (b) maintain the above code, compared to its original pure Java version."

I think to write articles about JavaFX/ Groovy code being "much simpler, effective, and less error-prone" than Java code is more appropriate on Groovy board.

And for articles about JavaFX there is a nice RIA Zone

Geertjan Wielenga replied on Mon, 2009/06/08 - 3:23am

I think to write articles about JavaFX/ Groovy code being "much simpler, effective, and less error-prone" than Java code is more appropriate on Groovy board.


So all you want on Javalobby are articles that are uncritical of Java? What qualifies this article for inclusion on Javalobby is the fact that it is about Java. The fact that it turns out that it doesn't FAVOR Java is completely and utterly irrelevant.

James Jamesson replied on Mon, 2009/06/08 - 3:49am in response to: Michal Hlavac

My quote "I wont use JavaFX because I do not need it, and like JavaScript, JavaFX aint Java". .

You have gotto be kidding me Michal. Let me rephrase it for you. I wont use JavaFX because I do not need it. And, like JavaScript, JavaFX is not Java. Point here is that a scripting language having a "Java" word in its name does not qualify it to be Java related.

I apologize for being harsh to you. With peace!

Jose Maria Arranz replied on Mon, 2009/06/08 - 3:50am

Groovy is a higher level language on top of "Java as platform", JavaFX is even more higher. Groovy, JavaFX and Java as language are different flavours of "Java as platform", it makes sense Groovy and JavaFX news in JavaLobby. Some day if overwhelming success of Groovy and JavaFX occurs, a and would be necessary to avoid too many news per day, and would be specialized in Java "as language".

Said this, I can understand JavaFX is the new cornerstone of the Sun (Oracle) offering and it is fine and needed, JavaFX can compete with Flash/Flex/AIR and Groovy has its place, but many people (myself included) think scripting languages are problematic to manage complex applications because of lack of a compiler (yes I know you can compile Groovy). Promoting the mantra "no pure Java code" can be appeling though can drive to bad decisions about the right technology to use.

Scripting has its place, really, in small applications (or applications repeating the same pattern again and again)  and highly dynamic applications wich need to read source code from external sources.

I've read again and again examples like:

def channel = new XmlParser().parse(url).channel 

"Now that's just plain cool, especially after comparing it again to the original monstrosity (in Java)."

Geertjan is not the language, is the API, the original code in Java is using a SAX parser, a SAX parser is a low level API for markup, using DOM would be shorter (I'm sure Groovy uses DOM behind the scenes), the method Document.getDocumentElement() returns the channel node. Using XPath and/or TreeWalker can help to traverse the DOM in a similar fashion you are doing in Groovy, yes the Java code would be slightly more verbose but who cares? Even more if you wrap some typical DOM code in a custom self made mini-API you have the same productivity as Groovy. There is one problem, you need to compile your Java code, you don't in Groovy and JavaFX, yes definitively Groovy, JavaFX etc are nice if compilation phase is a problem.

By the way, jamesjames, Geertjan works for SunOracle and I'm sure he does not want to kill Java... the language :)


James Jamesson replied on Mon, 2009/06/08 - 4:07am in response to: Jose Maria Arranz

I mostly agree. However, to me JavaFX should have its own zone like Groovy. Moreover, I never thought Geertjan would want to kill Java ;). It is just that the title of the article smells JavaFX marketing. I wonder if he is employed at the marketing and propaganda department at Sun, just kidding ;).

Felix Schrape replied on Mon, 2009/06/08 - 10:28am

If you are interested in Dierk König's talk on "JavaFX Programming Language + Groovy = Beauty + Productivity", you can view a .pdf of his slides here: Take a look at Dierk's Slides!

Fabrizio Giudici replied on Mon, 2009/06/08 - 11:01am

I think that it would make sense to *discuss* the creation of a JavaFX zone, but it would mostly for ... promoting JavaFX on its own.

For the rest, JavaFX is the only non-Java language that I'm using on the Java platform. I don't have any particular interest in Groovy, JRuby, Scala; nevertheless I regularly read articles about that stuff, generically because looking at things in different perspectivesis inspiring; because who knows, sooner or later I could change my mind (unlikely) or because I would have a better awareness in motivating my decision of sticking with Java (likely).

My point is that it's important that the title (or the first lines) describes the article content. In this case it does and if I'm not in the mood of reading about Groovy I don't find it hard to skip it.

Osvaldo Doederlein replied on Mon, 2009/06/08 - 11:22am

Groovy is Java. JavaFX is Java. Scala is Java. JRuby is Java. Repeat after me 100 times, "Java is a Platform".

Yes we have a Groovy Zone, and we should have a JavaFX Zone, at least if JavaFX content and interest are already big enough. But this particular article belongs here, exactly because it's a "language mashup" article. Notice: We don't have separated "Java Language Zone" and "Java Platform Zone", so the "Java Zone" must obviously accept any material that is relevant to Java-as-a-Platform. Perhaps we should have that separation, to avoid such stupid discussions.

What' next, people complaining of Java Zone articles that cover any API/framework that's not included in the ME/SE/EE platforms and not an official JCP API? "Move this crap to the Hibernate Zone", I can already hear...

Otengi Miloskov replied on Mon, 2009/06/08 - 4:01pm

Calm down people, This article is about Java and Groovy. It happend that JavaFX is the front end it could be JSF or JSP or GWT or even Flex. The point here  is between Java and Groovy and as I said if I will replace Java will be with Scala but I think the article is fine and critique Java flaws so we Java developers can learn from Groovy and apply those to Java. I dont see anything bad about this article because also Groovy is Java behind the scenes.

For JavaFX and Flex and even GWT there is a RIA zone, that zone is for that topics but sometimes we need a front end to explain the excersise of the article and happend to be in this article is JavaFX.

Personaly I dont like much JavaFX I prefer Flex but it is not bad to learn something new sometimes.

Otengi Miloskov replied on Mon, 2009/06/08 - 4:19pm

Also Im agree with the commenter that said he is a polyglot programmer in this times doing everything in just one language is plain dumb. For example I use C with Lua for low level stuff and high performance graphics, Python for Website or scripting tasks, Java for Business/Web apps and sometimes I used groovy for scripting Java, Flex/AS and Javascript for RIA/Web and at last Haskell because I love that language I do it as a hobby. So it is 8 languages I use this days depending of the project and the task plus when I was more young I learned Basic, Pascal, Clipper, x86 Assembly, Perl and little bit of PHP.

phil swenson replied on Mon, 2009/06/08 - 8:52pm

It seems like half the traffic on Java Lobby is people bitching about how a topic isn't "java" enough. Suggestion to the people who can't deal with a post that isn't "pure": read the title. If you aren't interested, skip it!

Leonel Gayard replied on Tue, 2009/06/09 - 9:34am

Guys, doesn't it strike you that users will also have to download Groovy's 1.6 MB jar file in order to get this simple app working ?

Also, this simple line of code:

def channel = new XmlParser().parse(url).channel

This is possible not because Groovy the language is cool (it is), but because its accompanying classes (the GDK) are awesome.

There are a lot of classes in the JDK for XML, but they aren't as simple to use.

This is a class I could easily see implemented in Java.

Instead of promoting language changes, we could wish for easier to use classes in the JDK.

Andres Almiray replied on Tue, 2009/06/09 - 12:10pm in response to: Leonel Gayard

In plain Java you would go as far as

XmlData xml = new XmlParser().parse(url)

calling .channel requires metaprogramming techniques that are simply not available in Java, so this is really a combination of language features and libraries. The thing is that both are so tighly integrated that a library feature can be mistaken for a language feature, like the following example demonstrates ;-)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.