blog rss feed

Using MigLayout with Swing for easier forms

Author: Dave Cherry last modified
Keywords: programming java

I've recently been working on a lot of Swing code and while doing so came across MigLayout java layout manager, and I believe that it really did make my life easier. Instead of using GridBagConstraints one can simply provide String constraints, in the example below I show how to build a simple form using the layout. Imagine how much code would be required to do this using GridBagLayout?

MigLayout is an all encompasing layout manager, that is kind of like a hybrid of FlowLayout, BorderLayout and GridBagLayout. Below I include an example form with two text fields and an OK button. If I had chosen to build this with GridBagLayout, I would have had to generate constriants objects and adjusted the row and column information. If I had chosen to use GridLayout, all the columns would have been the same size regardless of content.

In conclusion, there may be many other choices, but I am taken back by how quickly I solved real problems with this layout manager. More information can be found on the MigLayout site.

Example building a Swing Form

import java.awt.Container;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;

public class SwingMigLayout extends JFrame {
	SwingMigLayout() {
		Container formPanel = getContentPane();
		formPanel.setLayout(new MigLayout());
		
		formPanel.add(new JLabel("First Name:"));
		formPanel.add(new JTextField(20), "wrap");
		formPanel.add(new JLabel("Last Name"));
		formPanel.add(new JTextField(20), "wrap");
		formPanel.add(new JButton("Next"));
	}
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				SwingMigLayout sml = new SwingMigLayout();
				sml.pack();
				sml.setVisible(true);
				sml.setDefaultCloseOperation(EXIT_ON_CLOSE);
				sml.setTitle("Simple example of MigLayout");
			}
		});
	}
}

And the output..

Form panel built with MigLayout

Comments [2]

On 01-Dec-2009 23:58,  Nicolas wrote:

You might also be aware that javabuilders (http://javabuilders.org/) makes using MigLayout very easy.

On 02-Dec-2009 07:57,  Dave Cherry wrote:

Thanks Nicolas, I will take a look over in that direction!

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30