Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active December 26, 2015 09:09
Show Gist options
  • Save davidallsopp/7127264 to your computer and use it in GitHub Desktop.
Save davidallsopp/7127264 to your computer and use it in GitHub Desktop.
When writing Swing GUI code (in particular) we often have many repetitive calls to the same object. When using Swing from Scala, it would be nice to remove that duplication:
import javax.swing.JCheckBox
object SwingBuilder {
// Instead of this:
val checkbox = new JCheckBox()
checkbox.setText("Hello")
checkbox.setAlignmentX(0.0f)
checkbox.setLocation(0, 100)
// Use this:
def setup[T](t: T)(fs: T => Any*): T = { fs.foreach(_(t)) ; t }
// So we can set up widgets like this:
val checkbox2 = setup(new JCheckBox)(_.setText("Hello"), _.setAlignmentX(0.0f), _.setLocation(0, 100))
// It feels like there should be an easier built-in way to apply multiple methods
// like this, but I haven't found it yet...
// ... Update: here's one from http://stackoverflow.com/q/2705018/699224
// One can just create an anonymous subclass:
val checkbox3 = new JCheckBox() {
setText("Hello")
setAlignmentX(0.0f)
setLocation(0, 100)
}
// or use this variant so the object is fully constructed first
// (though the added awkwardness possibly outweighs the advantage)
val checkbox4 = new JCheckBox(); // NB newline or semicolon required
{
import checkbox4._
setText("Hello")
setAlignmentX(0.0f)
setLocation(0, 100)
}
// The nearest equivalent in Java is an instance initializer {{}}
// JButton button = new JButton()
// {
// {
// setText("Hello");
// setAlignmentX(0.0f);
// setLocation(0, 100);
// }
// };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment