GridBagLayout Tutorial

This tutorial shows you how to construct a complex Java Swing GUI using the GridBagLayout.

Let’s assume you have received a protoype sketch of how an application screen should look like, which you have been assigned to create :

It is a fairly complex user interface screen with a number of different controls, and with different component regions. Let’s sketch some lines to represent grid lines. Our GridBagLayout has gridX and gridY constraints which can be associated with the components we have sketched in our grid.

If we think about it for a while, we can see that not all regions fit into a grid cell, some regions spread into two cells (marked in blue) :

 

We can make the GridBagLayout make these two blue regions cover more than one cell using the gridWidth and gridHeight constraint.

***

So… let’s create a basic first cut of our GUI. The following code sets up the main components in the frame using GridBagLayout. At the moment we don’t have any components in the details panel to the right, so we will add a border on an empty panel to get a visual on where it should be on the frame.

Notice how one GridBagConstraint object is being created and being passed in with the component to the main panel? This constraint object holds all the information on how a component should be displayed. In our first cut, we are only interested in the X and Y placement, and spans, so we set gridX and gridY on all the first level components we are adding.

For our button panel at the bottom we set the gridWidth to 2, indicating that we want it to spread to the right by one more grid cell, and likewise with the details panel we want it to spill over into two cells. It is important to reset any constraint values (such as gridWidth) because we are dealing with only one constraints object.

Now when we run our program we will see this :

Well, it’s a start..

The two rows of buttons are looking good. Per default JPanels have a FlowLayout, laying out components from left to right in a centered fashion. This looks good for what our requirements are. Of course our label at the top needs to be left aligned, and our table would be good if it had some data in it.

We can anchor our label to the left quite easily by adding an anchor constraint.

Lets move on to our details panel on the right. This panel will also use a GridBagLayout, so we will effectively have two nested GridBagLayouts in our application frame. We’ll create this panel in a separate method, and add this panel to where our empty panel with the border was. In this first cut lets just concern ourselves with gridX and gridY constraints :

A useful technique is to use variables for X and Y coordinates. In our details panel, I have used an ‘I’ variable for the Y position. This makes it extremely easy to add extra fields at a later point in time.

Now lets see what we get :

Pretty awful huh..

All the components are in their correct X and Y positions but the width has to be fixed. The checkbox at the bottom is in its own separate column, so we need to stretch the text fields over to the right. We do this by setting the gridWidth property to two for those fields that we want to stretch over.

Set the width like this

remembering to set it back when you get to the labels!

Remember also that both label and field at the bottom have to have a width of one.

Now if we run it, it still looks terrible, but at least we see that we have three columns with most of the text fields sitting over the last two columns. Our text fields also need to ‘fill’ their space, so let’s add horizontal fill to the text fields, remembering to reset when we come to the labels.

Lets put our TextArea in a Scrollpane and add some dimensions.

The columns dimension in our text area will be overridden by our GridBagLayout, however our rows value (of 2) will not.

Lets also add Insets :

If we set them once at the top, they will flow through to all components.

Now the right side of our frame is starting to look much better :

All out labels should be aligned to the top-right (or NORTHEAST in gridbag speak)

We can put this alongside the insets (to affect all components) because our anchor does not affect our text field components, only our labels, since they have no FILL set.

The details panel is also hovering vertically in the center which doesn’t really look that good. We need to anchor the details panel to the NORTH on the outer GridBagLayout.

Our table should also stretch out in both directions, effectively swallowing up any space that may be available.

Weight X and weight Y should be set to 1.0 to prevent the table from collapsing upon a resize event.

Refactor out the ScrollPane and give it a preferred size. This gives you a bit of control over the fill of the table and scrollpane.

If you find some of the text fields on the right are collapsing, add some column width via the integer parameter when constructing text fields :

You should end up with something like this :

 

TIPS.

  • Because of all the switching around from one column to the second column. Ie resetting things like fills and anchors, it could be good idea to have 2 GridBagConstraint objects, one for each column
  • Textfields, textareas and tables should never collapse after the frame has called pack(). The collapse happens when the components size switches from preferred to minimum. This can be caused by a number of reasons. If you find textfields collapsing after resize then you should set their mimimum size to its preferred size :

source code


Posted in Swing | Tagged , , , , | 21 Comments

21 Responses to GridBagLayout Tutorial

  1. JD says:

    Fanstastic tutorial; thank you!

  2. Batou says:

    Great tutorial thank you!!

  3. Kanat says:

    Good Job, exactly what I needed!
    Thank you very much! All the best!

  4. Ash says:

    Hey
    This is really good but for some reason my createDetailsPanel does not show my textfields, labels when i run my program I dont know why.
    Do you know what I need to do to enable it to show and can you please put comments on your code so I know what it is used for.

  5. Ash says:

    Never mind i realised that i didnot read the source code properly thanks.

  6. Bella says:

    Heey..

    I have the same problem as Ash did and even though i read through the code I my createDetailsPanel don’t show up?

    Where are you creating the method? And there do you use it later?’

    AWESOME EXAMPLE.
    Thanks :-)

  7. Pingback: Gridbaglayout tutorial | Lunchtrac

  8. Pratheek says:

    Brilliant tutorial. Very well explained!

  9. Richard says:

    Totally awesome tutorial, you really saved my ass here. Really appreciate it

  10. Glib says:

    Thank you for your great tutorial, i read it tree times and each time i find something new :)

  11. Rodrigo says:

    Excellent! It could not be better explained! Was very helpful, thank you.

  12. ANONDREN says:

    Wow! this tutorial is very helpful, thank you

  13. Nirmal says:

    Hi,

    Thanks a lot for the example. I was trying out a same screen. I would like to know how can I bring the window in the middle of the screen. Could you please help me with this..

    regards
    Nirmal

  14. felixzacat says:

    Hi Nimal,
    try this :

    JFrame frame = new JFrame ();
    frame.setSize ( 500, 300 );
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );

  15. Marcelo Afanaci says:

    Man, you did a great job on this tutorial. It was very helpful to me. With a sketch and a couple of print screens you was very simple and direct.

    Thanks a lot and, Congrats.

  16. Naveed Ali says:

    Wonderful

  17. sabbir Jaman says:

    I can’t under stand

  18. sec.C says:

    One thing that is not described here and is really important, handling JScrollPane within a resizable GridBagLayout…

    I already went through the trouble a building a layout with two different JScrollPane that resize with the JFrame and I couldn’t do it without “cheating” and overrding few Swing related methods on the components.

    If someone found a way that is supported by the layout manager, I’m still looking for one…

  19. Tim Jackson says:

    This is the best tutorial I have used yet!
    I have spent over a $150 in books.

    Thanks

  20. Ciprian says:

    Super !
    This step=by-step example was exactly what I needed to understand GridBagLayout … It’s hard to understand it from oracle !

    Many thanks, again :D !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

THREE_COLUMN_PAGE