Tuesday, November 11, 2008

Why Swing UIs are so hard...

I'll tell you why - ok, well at least with issue I'm having now, which seems to be a common issue - LAYOUT.

How do you nicely lay out components? I've been reasonably happy with the layout tools NetBeans puts in for you. But I have a main window with 9 sub-panels, almost like portlets. Not all are the same size - and I want to have the user re-size them. Splitters? No, not the JSplitPane - too much overhead, can only split 2 sides. Enter the MultiSplitPane from SwingLabs - quite nice! An arbitrary grid layout even with custom split bars. BUT - how to specify a nice division. Well it provides "weight" - that's where the extra space goes. But what about the initial size? It uses each component's "preferred size" - seems like a good idea. But how do the components set their preferred size? This gets to the basic issue:

Layout - Bottom up or top down?
I attempted to have a component (tree control) set its preferred size based on the text and font it is assigned. Seems like a fine idea with good control, precision, etc. Nope! NullPointerException - the graphics aren't assigned at constructor time. Put in nice code:
String name = net.name;
FontRenderContext frc = ((Graphics2D)this.getGraphics()).getFontRenderContext();
TextLayout tl = new TextLayout(name, networkTree.getFont(), frc);
setPreferredSize(new Dimension((int)(tl.getBounds().getWidth()*1.5), 0));

NullPointerException at the line with getGraphics.

Top down...
Seems like Swing should learn from HTML/CSS - why can't a table support column widths in percentages? Seems like a simple enough thing - so I'm off to try banging that into MultiSplitPane.

2 comments:

Greg said...

Have you tried and of the www.instantiations.com UI building stuff?

Engineer Dude said...

Greg: thanks for the comment - just now saw it! ???
I haven't tried that one - a colleague here has it. I keep seeing it in the context of SWT guis? The GUI Builder in NetBeans these days is actually quite good - there just doesn't seem to be a layout manager which handles proportional layout - e.g. 25%/30%/20%/25%. MigLayout seems to be the end-all on that front, but of course it doesn't integrate with a builder :(