Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..
SYS-CON.TV
Today's Top SOA Links


TableLayout: Replace Your GridBag Layout Code
Introducing a robust but easy-to-use LayoutManager for use in any Java Swing application

In this month's article I introduce TableLayout, a robust but easy-to-use LayoutManager for use in any Java Swing application. It's based very loosely on the HTML TABLE paradigm, where components are placed in table cells in row-major order. Vertical and horizontal alignment for the component in a cell can be specified, and a component (cell) may span rows and columns. I also present Forms-Panel, a JPanel sub-class that abstracts the underlying TableLayout.

This article assumes you have some familiarity with the design and use of LayoutManagers in Swing.

Background
I have been doing Java Swing applications for many years, and I've never been comfortable using a GUI designer tool, both for the verbose and often horrible Java code they produce and the lack of support for anything other than absolute positioning and sizing of components. I suspect that the quality of these tools has improved tremendously in recent years, but I'm stuck in my ways and have come to be fairly productive in laying out a user interface without the help of a visual design tool. (I have done some desktop application development in C# using Visual Studio .NET, which forces you to use the visual designer of this IDE. I was actually surprised at how productive I could be in this environment, and C# does not have the LayoutManager concept, so perhaps there is hope for me.)

I have found the LayoutManager concept in Swing to be truly inspired, but powerful and easy-to-use implementations a little wanting. My idea of a good LayoutManager is one that is fairly robust yet doesn't require a big learning curve to use or a lot of code to implement. I believe that the code used to lay out a user interface should be fairly self-documenting. In this regard, I have never been a fan of GridBagLayout and its necessary but evil companion, GridBagConstraints. I certainly recognize the power and capability of this LayoutManager, but I have found it difficult to learn and use, and even harder to maintain code that uses it.

I once led a team of UI developers in which I decreed (because I could) that the use of GridBagLayout would not pass code inspection. Fortunately, we had my TableLayout. I have used one form or another of it on several different projects over the years, and it has slowly evolved during this time as well. I would often maintain that any user interface could be done using a combination of BorderLayout and my TableLayout, given the willingness to subdivide the layout into separate and distinct grids (JPanels).

TableLayout Concepts
TableLayout uses a grid to lay out UI components, which is desirable, since good UI design involves the use of the grid concept. In contrast to Swing's GridLayout, TableLayout does not force every cell in the grid to be the same width and height. (I have never found GridLayout to be useful for much of anything other than a calendar or calculator application.) Rather it lets the preferred height of all the components in a row control the row height, and the preferred width of each component in a column control the width of the column. This by itself is not a new or original concept, but TableLayout brings some other things to the "table" as well. First, it supports the idea of extending the last row or column in the layout to the containing parent's boundaries. Second, it allows you to control the vertical and horizontal alignment of a component in a cell and to have cells span rows and columns if necessary. These are both optional behaviors, and TableLayout takes reasonable defaults so that it can be used in a very straightforward manner to easily lay out a sensible user interface.

CellConstraint
Cell alignment and row/column spanning are controlled using the CellConstraint object, which is only needed to specify something other than the default alignment or spanning. The CellConstraint class has several different constructors, but the easiest one to use is:

public CellContraint(String encoding);

In fact, TableLayout will accept a String as a constraint argument (the Container's add() method) and invoke this CellConstraint constructor for you (you'll see this in all example code). The encoding is a comma-separated list of name-value pairs that specify alignment and spanning, very similar to HTML TABLE attributes. Supported attributes are align, vAlign, rowSpan, and colSpan (case-insensitive). align is used for horizontal cell alignment and accepts case-insensitive values of left, center, right, or fill. vAlign is used to specify vertical alignment for a cell, with values of top, middle, bottom, or fill. The default value for align is fill, while the default value for vAlign is middle. rowSpan and colSpan each take a numeric argument indicating the number of rows or columns to span. As with the HTML table, a value of 0 for rowSpan or colSpan means to span to the end of the row or column. Table 1 summarizes the CellConstraint values.

You can specify these values directly in other CellConstraint constructors if desired. For example:

CellConstraint c = new CellConstraint
(2, 1, TagValue.LEFT, TagValue.MIDDLE);

is identical to:

CellConstraint c = new CellContraint("colspan=2, align=left");

Both create a CellContraint for spanning two columns, with a left horizontal alignment.

Using TableLayout
TableLayout has several constructors that are similar to the constructors for GridLayout and accomplish the same. As with GridLayout, you can specify either the number of rows or the number of columns to be zero, but not both. TableLayout has constructors that let you control whether or not the last column in the container is filled, or the last row in the container is filled. The default for the former is true, the latter, false. TableLayout provides getter and setter methods for these attributes as well as the horizontal and vertical spacing between table cells. How does application code that uses TableLayout compare to one that uses GridBagLayout? Consider Figure 1, an example of a simple login dialog box.

The dialog consists of three separate components:
the top "form" where the login parameters are entered, a horizontal line (normally the horizontal line separator would be accomplished with a custom border around one of the other two panels, but having a component rendering this more clearly demonstrates the capabilities of TableLayout; we'll see this FormSeparator component again later in this article), and a button panel with two buttons. The dialog uses a TableLayout consisting of one-column (and zero rows) to position these three components. The "form" panel uses a two-column (zero rows) TableLayout.

You can run the LoginDialog test application that comes with the code for this article to create Figure 1. Note that the "User id: " and "Password" labels are left-aligned. Actually, they just use the default horizontal alignment, which is fill. Some UI designers believe that labels in a form should be right-aligned. Invoke the LoginDialog test application with the commandline argument align=right, and you'll see the dialog in Figure 2, which has right-aligned labels.

Figure 3 shows the same dialog produced using a GridBagLayout for the login form panel, while Listing 1 shows the code snippet used to produce the two different versions.

From Listing 1, you can clearly see that with TableLayout, less code is involved, the code is self-documenting (components are laid out in row-major order), and the code is more maintainable. (Imagine having to insert an additional component in the login form of the dialog. With TableLayout, that is very straightforward; not so with GridBagLayout, as the additional layout code will likely affect the layout code for components below the new one.) Note the use of the static TableLayout getFillerComponent() method to create the empty cell below the "Password" label and force the JCheckBox into the next column.

The TableLayoutDemo class provided with this article's code further demonstrates the capabilities of this LayoutManager. Figure 4 shows the resulting window. A TableLayout is used to lay out this JFrame, and a sub-panel using a TableLayout contains the nine JButton components. This TableLayout is manipulated using the sliders and checkboxes, which dynamically modify the corresponding TableLayout properties.

Listing 2 shows the code used to lay out the nine buttons. Note the alignment values for four of the buttons, and the corresponding behavior as the TableLayout attributes are modified.

Figures 5-8 show the effects of dynamically changing the TableLayout properties given the alignment attributes in Listing 2 (see Figure 5...Figure 6...Figure 7...Figure 8).

To demonstrate row and column spanning, run the ComplexTableLayout class provided with this article's code. Figure 9 shows the resulting window, and Listing 3 shows the code used to produce this.

Note the order in which the components are added to the layout. This would be done very similarly for an HTML table.

How It Works
The code for TableLayout is straightforward enough. As components are added to the parent container using a CellConstraint (addLayoutComponent() method), TableLayout ensures that every cell is mapped to a row and column position. Components that span a row or column leave "reserved" cells around them. An inner class, CellData, is used to hold the component and the constraint for each cell.

The actual child component layout and preferred size calculation for the parent Container is done in the layoutContainer() method. First, all of the preferred sizes for each child component are obtained. Based on this information, TableLayout is able to calculate the maximum height for each row and the maximum width for each column, i.e., the bounds for each cell. Given the cell bounds, each cell component is assigned its location and size, adjusting for any alignment and spanning. The size of each component in a last row or column is also adjusted if the layout is filling the last row or column. Finally, the preferred size of the parent Container is calculated given the cell boundaries and the spacing between each row and column.

About Phil Herold
Phil Herold is VP and CTO of PocketScience LLC in Research Triangle Park, NC. He has over 24 years of experience in software engineering, and has been working with Java client technologies since 1996.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 2

Actually, a table can easily be transformed into a GridBagLayout (even with cells of different sizes). Here's a tool that does exactly that, using a HTML table for defining the layout:

That tool even kills two birds with one stone, as it naturally allows you to document the layout in HTML as well.

The link I posted in the feedback for this article previously doesn't work any longer (for some reason). If you read the online version of the article, and click on the any of the "Listing" links, you'll be taken to a page that has a link to the entire Eclipse project, as a ZIP file. Here is that link:

http://res.sys-con.com/story/dec05/163311/TableLayout_Project.zip

I'm sorry you had trouble finding the code. I hope this helps.

--
Phil

Hi,
I have been searching all over this site for the source code link for your article. It is nowhere to be found. Can you help and point me in the right direction?
Thank you.

Chris,

The link is posted below in some of the other feedback comments. Sorry you had trouble finding the link to the source.

Good luck.

--
Phil

hi -

there is no link to the sourcecode for this article "TableLayout: Replace Your GridBag Layout Code", in the magazine, or in this online version. Where can I find the link to download the sample code ?

Thanks,
Chris.

Lance,

I'm sorry you had trouble finding the source to the article. This is, of course, out of my control. I will be sure to pass your comments on to the JDJ folks. I realize that it's definitely not obvious how to get the source, especially for print-only readers.

FWIW, I had also posted a link to the source in the feedback comments below. Thanks for your comments.

Took me a while to figure how to get the source code. Am I supposed to just know that it would be buried in a link posted in the comments on the article? The link that appears to link the the source is in a tiny box buried amongst other boxes and actually links back to the page you are on while looking at the link.

This site could use a good scrubbing of all the confusing extraneous garbage. As others have mentioned, if it takes me 5 minutes to find the source because you hide it, it is not worth the trouble and you may as well not bother.

Alan got it right. The clutter is out of control. Nice article but I spent an hour *searching* for a download link to the layout manager - the hour I might have used to try it out. Now I don't care - another reason I'm not bothering to renew my subscription when the renewal comes along.

Trackback Added: Bad Developers gone wild; Java Developer’s Journal Cover Story: Table Layout
— In this month’s article I introduce TableLayout, a robust but easy-to-use LayoutManager for use in any Java Swing application. It’s based very loosely on the HTML TABLE paradigm,...

Ravi:

The article was not about comparing my implementation of TableLayout to other existing ones. It was about an easy to use yet powerful layout manager that could be used in a Swing application. It just happened to have a class name that conflicted with other, similar implementations. I guess this is the first time that this has happened in the history of software development. I'll be more careful next time.

Since you asked, the features of my TableLayout are row / column spanning and last row / column filling, in addition to an API that uses a CellConstraint object but allows that to be easily constructed via a String, which makes the resulting code that uses my TableLayout self-documenting. I have no idea if these features compare favorably or unfavorably with other implementations, and I don't really care.

The article also presented a technique to abstract my TableLayout into another component, essentially hiding it's implementation. The custom FormsPanel class (of my own making, btw) I presented was inspired by JGoodies, but it is otherwise unrelated. I apologize if this was not clear in the article.

I hope the article introduced some developers to another way of doing things besides relying on GridBagLayout, and direct e-mail communication to me from several folks has indicated to me that I succeeded in that regard.

Finally, articles in JDJ are not represented as entire solutions, but are meant to illustrate techniques and ideas that other developers can borrow from in their every day work. I believe my article contained several instances of this. As one example, I showed how I could effect the layout of my application by specifying a command line argument, essentially one of the cell constraints (for labels). One could easily adapt this technique to having layout parameters specified in a ResourceBundle.

Thanks again for playing.

Even after reading the article multiple times, all I could find is a reference to JGoodies Forms functionality and how "TableLayout" could be used to enhance forms functionality provided by JGoodies. I am still missing the part where it was made clear that this is not the first and only implementation available.

There is a place where a statement goes like

"This by itself is not a new or original concept..."

but clearly, here the reference is to the concept of table layout, which obviously existed since the early days of HTML (I am not sure which version of HTML spec had it the first time).

If the article is about some new features that are not there in the other implementations or advantages that this new implementation has compared to the existing implementations, I would assume a reference would be given to at least one other implementation.

Ravi

Ravi:

I believe in my article I acknowledged that the concept was not original. There's at least two TableLayout implementations (besides mine) that I'm aware of. I don't know which TableLayout came first, though it really doesn't matter. I believe mine offers a couple of ideas that the others don't, and likely lacks several (or more) things that the other ones provide. Certainly the API for my implementation is different than the other ones, and it is a fairly light weight solution (only two class files--TableLayout.java and CellConstrainsts.java). That might make it attractive to some folks over the other implementations. Maybe not. But having the freedom to choose is great.

Yes, it may be unfortunate that the names collide, but I think my class name accurately describes what it does, and the name space is only so large. If I had called it PhilsTableLayout or TableLayoutDeux would it have been any more palatable for you? I would guess that it wouldn't.

And regardless, the most important thing is to get that awful GridBagLayout code out of your system.

Thanks for your comments.

Phil:

After reading your article which had a statement

"... Fortunately, we had my TableLayout.",

I started wondering if you developed a new flavor of a layout manager that already existed for years. I had used the TableLayout by Daniel Barbalace (https://tablelayout.dev.java.net/), which had a plug-in available to integrate with NetBeans back in Nov 2003. To confirm, I checked your source code and it looks like you did write a new layout manager with that exact same name as the old one.

I think, it would have been better had you looked around first to see if there is already a well established product out there... before writing your own version and dumping one more flavor of an age old thing on the Java community to confuse things?

Ravi

Here is the link to the source for the article. It's a ZIP file of the Eclipse project I used. Enjoy!.

http://res.sys-con.com/story/dec05/163311/Herold_TableLayout_Project.zip

Hey Guys,
You can get everything you need here:
https://tablelayout.dev.java.net/


Feedback Pages:


Your Feedback
Faulkston wrote: Actually, a table can easily be transformed into a GridBagLayout (even with cells of different sizes). Here's a tool that does exactly that, using a HTML table for defining the layout: That tool even kills two birds with one stone, as it naturally allows you to document the layout in HTML as well.
Phil Herold wrote: The link I posted in the feedback for this article previously doesn't work any longer (for some reason). If you read the online version of the article, and click on the any of the "Listing" links, you'll be taken to a page that has a link to the entire Eclipse project, as a ZIP file. Here is that link: http://res.sys-con.com/story/dec05/163311/TableLayout_Project.zip I'm sorry you had trouble finding the code. I hope this helps. -- Phil
Mike Piazza wrote: Hi, I have been searching all over this site for the source code link for your article. It is nowhere to be found. Can you help and point me in the right direction? Thank you.
Phil Herold wrote: Chris, The link is posted below in some of the other feedback comments. Sorry you had trouble finding the link to the source. Good luck. -- Phil
Chris Willison wrote: hi - there is no link to the sourcecode for this article "TableLayout: Replace Your GridBag Layout Code", in the magazine, or in this online version. Where can I find the link to download the sample code ? Thanks, Chris.
Phil Herold wrote: Lance, I'm sorry you had trouble finding the source to the article. This is, of course, out of my control. I will be sure to pass your comments on to the JDJ folks. I realize that it's definitely not obvious how to get the source, especially for print-only readers. FWIW, I had also posted a link to the source in the feedback comments below. Thanks for your comments.
Lance wrote: Took me a while to figure how to get the source code. Am I supposed to just know that it would be buried in a link posted in the comments on the article? The link that appears to link the the source is in a tiny box buried amongst other boxes and actually links back to the page you are on while looking at the link. This site could use a good scrubbing of all the confusing extraneous garbage. As others have mentioned, if it takes me 5 minutes to find the source because you hide it, it is not worth the trouble and you may as well not bother.
Rob wrote: Alan got it right. The clutter is out of control. Nice article but I spent an hour *searching* for a download link to the layout manager - the hour I might have used to try it out. Now I don't care - another reason I'm not bothering to renew my subscription when the renewal comes along.
Marcus S. Zarra wrote: Trackback Added: Bad Developers gone wild; Java Developer’s Journal Cover Story: Table Layout — In this month’s article I introduce TableLayout, a robust but easy-to-use LayoutManager for use in any Java Swing application. It’s based very loosely on the HTML TABLE paradigm,...
Phil Herold wrote: Ravi: The article was not about comparing my implementation of TableLayout to other existing ones. It was about an easy to use yet powerful layout manager that could be used in a Swing application. It just happened to have a class name that conflicted with other, similar implementations. I guess this is the first time that this has happened in the history of software development. I'll be more careful next time. Since you asked, the features of my TableLayout are row / column spanning and last row / column filling, in addition to an API that uses a CellConstraint object but allows that to be easily constructed via a String, which makes the resulting code that uses my TableLayout self-documenting. I have no idea if these features compare favorably or unfavorably with other implementations, and I don't really care. The article also presented a technique to abstract my TableLayout...
Ravi wrote: Even after reading the article multiple times, all I could find is a reference to JGoodies Forms functionality and how "TableLayout" could be used to enhance forms functionality provided by JGoodies. I am still missing the part where it was made clear that this is not the first and only implementation available. There is a place where a statement goes like "This by itself is not a new or original concept..." but clearly, here the reference is to the concept of table layout, which obviously existed since the early days of HTML (I am not sure which version of HTML spec had it the first time). If the article is about some new features that are not there in the other implementations or advantages that this new implementation has compared to the existing implementations, I would assume a reference would be given to at least one other implementation. Ravi
Phil Herold wrote: Ravi: I believe in my article I acknowledged that the concept was not original. There's at least two TableLayout implementations (besides mine) that I'm aware of. I don't know which TableLayout came first, though it really doesn't matter. I believe mine offers a couple of ideas that the others don't, and likely lacks several (or more) things that the other ones provide. Certainly the API for my implementation is different than the other ones, and it is a fairly light weight solution (only two class files--TableLayout.java and CellConstrainsts.java). That might make it attractive to some folks over the other implementations. Maybe not. But having the freedom to choose is great. Yes, it may be unfortunate that the names collide, but I think my class name accurately describes what it does, and the name space is only so large. If I had called it PhilsTableLayout or TableLayoutDeux woul...
Ravi wrote: Phil: After reading your article which had a statement "... Fortunately, we had my TableLayout.", I started wondering if you developed a new flavor of a layout manager that already existed for years. I had used the TableLayout by Daniel Barbalace (https://tablelayout.dev.java.net/), which had a plug-in available to integrate with NetBeans back in Nov 2003. To confirm, I checked your source code and it looks like you did write a new layout manager with that exact same name as the old one. I think, it would have been better had you looked around first to see if there is already a well established product out there... before writing your own version and dumping one more flavor of an age old thing on the Java community to confuse things? Ravi
Phil Herold wrote: Here is the link to the source for the article. It's a ZIP file of the Eclipse project I used. Enjoy!. http://res.sys-con.com/story/dec05/163311/Herold_TableLayout_Project.zip
Todd wrote: Hey Guys, You can get everything you need here: https://tablelayout.dev.java.net/
Thad wrote: Where can I download the source for this article? What good is this article if I can't get a copy of the TableLayout package?
Alan wrote: Where is the source code? This is the most cluttered web site I've ever seen.
JDJ News Desk wrote: Java Developer's Journal Cover Story: Table Layout. In this month's article I introduce TableLayout, a robust but easy-to-use LayoutManager for use in any Java Swing application. It's based very loosely on the HTML TABLE paradigm, where components are placed in table cells in row-major order. Vertical and horizontal alignment for the component in a cell can be specified, and a component (cell) may span rows and columns. I also present Forms-Panel, a JPanel sub-class that abstracts the underlying TableLayout.
SYS-CON Italy News Desk wrote: Java Developer's Journal Cover Story: Table Layout. In this month's article I introduce TableLayout, a robust but easy-to-use LayoutManager for use in any Java Swing application. It's based very loosely on the HTML TABLE paradigm, where components are placed in table cells in row-major order. Vertical and horizontal alignment for the component in a cell can be specified, and a component (cell) may span rows and columns. I also present Forms-Panel, a JPanel sub-class that abstracts the underlying TableLayout.
SYS-CON Netherlands News Desk wrote: Java Developer's Journal Cover Story: Table Layout. In this month's article I introduce TableLayout, a robust but easy-to-use LayoutManager for use in any Java Swing application. It's based very loosely on the HTML TABLE paradigm, where components are placed in table cells in row-major order. Vertical and horizontal alignment for the component in a cell can be specified, and a component (cell) may span rows and columns. I also present Forms-Panel, a JPanel sub-class that abstracts the underlying TableLayout.
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE