Thursday, December 11, 2008

Creating Applets with Scala

Upon the recently release of JavaFX 1.0, I became interested in exploring Scala's Swing cababilities.
I pefer a classical client-server application, as opposed to the ever popular web-based apps using AJAX as a rich content enabler.
So this is right up my alley.



JavaFX Script (the language used to create GUI applictions in JavaFX) seems nicer than many of the XML-base GUI DSLs (Microsoft Silverlight),
but I'm in the mist of learning Scala and this seems like a good problem to solve with Scala's DSL making features.



Fortunatly, someone has already done the heavy lifting and created a small, but useful layer on to top of Swing. It was recently
included in the lastest release of Scala (2.7.2), So here I go.



I stared with a generated maven archetype from the scala-tool.org repository





1 mvn archetype:generate -DarchetypeCatalog=http://scala-tools.org



Then I add the folowing code the the App.scala file generated by the archetype:





1 package org.samples.gui
2
3 import scala.swing._
4 import scala.swing.event._
5
6 class App extends Applet {
7
8 object ui extends UI with Reactor {
9
10 def init() = {
11
12 val button = new Button {
13 text = "Click me"
14 }
15
16 val label = new Label {
17 text = "Welcome to Hello, World Applet"
18 }
19
20 contents = new BoxPanel(Orientation.Vertical) {
21 contents += button
22 contents += label
23 border = Swing.EmptyBorder(30, 30, 10, 30)
24 }
25
26 listenTo(button)
27
28 reactions += {
29 case ButtonClicked(b) => label.text = "Hello, World"
30 }
31 }
32 }
33 }



Next, I added an HTML file to my project (src/main/resources/App.html)





1 <h1>Hello, World Applet</h1>
2
3 <div>
4
5 <applet width = "300" height = "100" code = "org.samples.gui.App.class"
6
7 archive = "/home/erick/projects/samples-scala-gui/target/samples-scala-gui-1.0-SNAPSHOT.jar,
8 /home/erick/.m2/repository/org/scala-lang/scala-library/2.7.2/scala-library-2.7.2.jar,
9 /home/erick/.m2/repository/org/scala-lang/scala-swing/2.7.2/scala-swing-2.7.2.jar">
10
11 <strong>this browser does not understand java.</strong>
12
13 </applet>
14
15 </div>

No comments:

Total Pageviews

Labels