Thursday, 29 April 2010

Miglayout DSL

Here's an embryonic DSL for MigLayout in Java.  Statically imported enums turn out to be a pretty handy alternative to Smalltalk or Erlang atoms.  Unfortunately I can't find the HTML syntax highlighter for Java.


import static MigBuilder.*;

Object mig = mig(size(BUTTON_WIDTH, BUTTON_HEIGHT), gapleft(LEFT_GAP), hidemode(zero), growx, growy);
        
String migconstraint = "w 11!, h 52!, gapleft 3, growx, growy";

enum MigBuilder {
  grow, growx, growy, push, gapleft;
 
  public static Object mig(Object...strings)
  {
    StringBuilder builder = new StringBuilder();
    for (Object object : strings)
    {
      if(object instanceof MigBuilder)
        builder.append(',');
     
      builder.append(String.valueOf(object));
    }
    return builder.toString();     
  }
 
  public static Object size(int width, int height)
  {
    return mig("w ", width, "!,h ", height, '!');
  }
 
  public static Object gapleft(int pixels)
  {
    return mig(gapleft, pixels);
  }
 
  public static Object hidemode(HideMode hidemode)
  {
    return mig("hidemode ", hidemode);
  }
}

No comments: