Feb 3, 2015

Show the Structure of Your GUI in Your Code

I LIKE creating my GUIs programmatically. I suppose I'm a traditionalist (some would say a masochist). But I feel that it gives me more control over the design and keeps together things that should live together.

The downside to this is, lots of objects all declared in the same scope, with no structure to give you a hint as to how they all fit together:

    class View {
      Form frm = new Form();
      FlowLayoutPanel pnl = new FlowLayoutPanel();
      TabControl tbc = new TabControl();
      TabPage tbp1 = new TabPage();
      Label lbl = new Label();
      TextBox txt = new TextBox();
      TabPage tbp2 = new TabPage();
      Button btn = new Button();
      ...
    }
If you think about it though, the controls will all have fixed parent-child relationships with each other. They will effectively form a tree structure during runtime, that will give rise to the final graphical display. In fact, that's what all the XAMLs and JavaFXs and QMLs of the world model. Why not actually show these relationships in the code itself with a little bit of indentation trickery?

    class View {
      Form frm              = new Form();
        FlowLayoutPanel pnl = new FlowLayoutPanel();
          TabControl tbc    = new TabControl();
            TabPage tbp1    = new TabPage();
              Label lbl     = new Label();
              TextBox txt   = new TextBox();
            TabPage tbp2    = new TabPage();
          Button btn        = new Button();
      ...
    }

A-ha! So the Button won't be inside the TabPage; it'll be a sibling of the TabControl itself!

Of course, this is all manual, and won't work with whitespace-sensitive languages, and can get out of date when you change your layout, and all those things. But--when it does work, it's surprising how well it works at organising my thoughts about the layout into a nice 'graphical' overview.