Creating a Java/Swing GUI with RiverLayout
by Peter Stuifzand, June 2005
Creating GUIs in Java can be difficult and most of the time is is too much work. I will show how you can create a nice Java GUI without doing all the work you normally would have to do.
Creating a GUI in Java is hard work. Sometimes it just is too much. In this article I will show two components that will increase your performance and help you create beautiful GUIs.
RiverLayout
RiverLayout is a LayoutManager that helps you create simple form layouts. With every component you add to a panel you can specify a constraint. The nice thing is that these contraints are really simple.
RiverLayout can be downloaded from www.datadosen.se/riverlayout and is released under a LGPL license. You can unzip it in the same directory as your source code.
| br | Adds a line break. The next component will be placed below this component. |
| p | Add a paragraph break. The next component will be placed below this component, but lower than with the `b`. |
| tab | Add a tab stop. This can be used to align labels and fields. |
| hfill | Horizontal fill. This component will be filled to the right as far as possible. |
| vfill | Vertical fill. This component will be as high as possible. |
There are a few other constraints possible. These other RiverLayout constraints can be found in the javadocs.
JPanel panel = new JPanel(new RiverLayout());
panel.add("p left", new JLabel("Please enter a search term: "));
panel.add("br hfill", new JTextField());
panel.add("", new JButton("Search"));
The next image shows how these four lines of code will look. It's a search interface that could be used to search for some terms on the internet.

RiverLayoutSample1.java source code
Every line of code is as simple as it could get. First we create a new
JPanel with the RiverLayout as its LayoutManager. After that, we
create the components. For each component we specify the
constraint. The line with constraint p fill will create a JLabel in
a new paragraph with left justification.
As you can the next line creates a JTextField that is horizontally filled on the next line. We do not specify any constraints for the JButton. It will be placed after the JTextField on the same line.
Another nice thing about this layout is that it will resize whenever you change the size of the window in which it is created.
If you have any ideas, suggestions or found a bug please mail me.