Anyone who has written a non-trivial amount of Swing will know the pain of menu definitions. They’re amazingly verbose.
Metascope used a reasonably large number of menus, and this verbosity had started to bother me, so I came up with a few syntactic hacks to clean it up. A “DSL” if you prefer. The result was relatively terse in comparison (only one superfluous line of code and two superfluous lines for the braces per menu item! In Java terms that’s practically a one liner).
Here’s essentially the same idea ported to Scala, with a few additional cute hacks and taking advantage of Scala’s first class functions to make it terser yet.
Some sample code:
val frame = new JFrame(){} frame.setJMenuBar(new MenuBar{ new Menu("File"){ "Save" does { } "Open" does { } --- "Quit" does { System.exit(0) } } new Menu("Edit"){ "I like kitties" is true toggles (x => if(x) println("I like kitties") else println("I appear to be lying")) new Menu("A sub menu"){ "There are no kitties in this submenu" does { } } } }); frame.setSize(500, 500); frame.setVisible(true);
The rest of the code to make this work is available here.
I loved it.
Maybe we need a complete Scala Swing wrapper, did anybody attempt that?
Yes, there’s the scala-swing wrapper that was released recently. I use the term “released” advisedly though. There’s no documentaiton, the source code kills scaladoc and it’s only available as an sbaz package.
It also doesn’t seem to do anything like this. :-)
I love it — groovy also has the SwingBuilder to make it less painful as well. However i hate swing so much i refuse to try it.
Yeah, Swing’s not the nicest. I’m probably going to write up something identical for QT Jambi, but it was easier to demonstrate the concept for Swing as people will already have that available.
Quickly looking at the Groovy SwingBuilder, it appears to be a fair bit noisier for this sort of thing (see e.g http://java.sun.com/developer/technicalArticles/JavaLP/groovy/ )
Not to the point where I’d actually consider it a big deal, but definitely noticable.