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.