Thursday, October 3, 2013

Getting Started With GroovyFX

To run GroovyFX programs we need to have groovyfx.jar and jfxrt.jar added to the classpath. The JDK I am using is v1.8.0-ea. JavaFX SDK is bundled with JDK from Java 7u4 and above.

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Intro.groovy: 3: unable to resolve class groovyx.javafx.GroovyFX
@ line 3, column 1.
import groovyx.javafx.GroovyFX
^

1 error
The above error is thrown if groovyfx.jar is not found. The easiest way to fix this would be to use Grapes and annotate the source with @Grab('org.codehaus.groovyfx:groovyfx:0.3.1'), which will download and add the groovyfx-0.3.1.jar in the .groovy directory. Another way would be to download it from maven repository and add it to classpath manually (or use mvn).
To add it manually, create a environment variable with name CLASSPATH with value .;F:\javaLibs\groovyfx-0.3.1.jar; (update the path F:\javaLibs to reflect your directory preferences). In Windows the delimiter is ; where as under GNU/Linux it is :. This example uses Windows. There is a dot at the beginning so that the current working directory is also included. If the variable already exists, just append it to the end preceeding the appropriate delimiter.

Caught: java.lang.NoClassDefFoundError: javafx/application/Application
java.lang.NoClassDefFoundError: javafx/application/Application
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
The above error is caused because Groovy could not find the jfxrt.jar file in the classpath. To resolve this append %JAVA_HOME%\jre\lib\jfxrt.jar; to the classpath variable.

The value of the CLASSPATH should look like
.;F:\javaLibs\groovyfx-0.3.1.jar;%JAVA_HOME%\jre\lib\jfxrt.jar;
These are the two main errors that gets between running GroovyFX programs. Let us run a sample program from the groovyfx.org website.
// Hello.groovy
import groovyx.javafx.GroovyFX

GroovyFX.start {
stage(title: "GroovyFX Hello World", visible: true) {
scene(fill: BLACK, width: 500, height: 250) {
hbox(padding: 60) {
text(text: "Groovy", font: "80pt sanserif") {
fill linearGradient(endX: 0, stops: [PALEGREEN, SEAGREEN])
}
text(text: "FX", font: "80pt sanserif") {
fill linearGradient(endX: 0, stops: [CYAN, DODGERBLUE])
effect dropShadow(color: DODGERBLUE, radius: 25, spread: 0.25)
}
}
}
}
}
Run it as
groovy Hello.groovy
or compile and run as
groovyc Hello.groovy
groovy Hello
will give the output as shown below.

GroovyFX