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(){}

"Save" does { }
"Open" does { }
---
"Quit" does { System.exit(0) }
}
"I like kitties" is true toggles (x => if(x) println("I like kitties") else println("I appear to be lying"))
"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.

This entry was posted in programming and tagged , on by .

5 thoughts on “Make your menu definitions less irritating”

1. david Post author

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. :-)

2. david Post author

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.