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.