Home > Articles > Programming > Java

Harness the Power of Java's GridBagLayout

In part 1 of a three-part series that explores the much-maligned GridBagLayout layout manager, Jeff Friesen introduces you to the GridBagLayout and GridBagConstraints classes. Jeff also presents a demonstration application that illustrates how to get the constraints just right.
Like this article? We recommend

GridBagLayout (one of Java’s original layout managers) has a bad reputation among Java developers. According to Ethan Nicholas’ "Reinventing GridBagLayout" blog entry, this layout manager is "ridiculously difficult to use." In a more extreme case, the author of a late 1990s Java book was loosely quoted as hating GridBagLayout. I hope that this series will improve GridBagLayout’s reputation.

I’ve divided this series into three articles. Part 1 (this article) introduces GridBagLayout, where you learn how to work with the java.awt.GridBagLayout and java.awt.GridBagConstraints classes. Part 2 uses GridBagLayout to lay out an address book GUI, which demonstrates this layout manager’s effectiveness in laying out realistic GUIs. In case you’re still not impressed with GridBagLayout, part 3 presents the JGoodies FormLayout alternative, and compares this layout manager with GridBagLayout so you can choose the layout manager that works best for you.

Introducing GridBagLayout

GridBagLayout consists of two classes: GridBagLayout and GridBagConstraints. GridBagLayout aligns components vertically and horizontally within a grid of rows and columns. Rows can have differing heights, and columns can have differing widths. GridBagLayout places components into cells—the intersections of rows and columns. A single component can occupy multiple cells; the region of cells that a component occupies is known as the component’s display area.

The grid’s orientation depends on the container’s ComponentOrientation—a property that encapsulates the language-sensitive orientation used to order the elements of a component or of text:

  • For horizontal left-to-right orientations, grid coordinate (0,0) is in the upper-left corner of the container: x increases to the right and y increases downward.
  • For horizontal right-to-left orientations, grid coordinate (0,0) is in the upper-right corner of the container: x increases to the left and y increases downward.

Before displaying a component, GridBagLayout considers the component’s minimum and preferred sizes when figuring out the component’s size. GridBagLayout also considers the component’s associated GridBagConstraints, which specifies where a component’s display area should be located on the grid, and how the component should be positioned within its display area. GridBagConstraints offers this information via the following constraints field variables:

  • gridx and gridy identify the cell that contains the leading corner of the component’s display area: 0 values in these fields identify the cell at the grid’s origin. For horizontal left-to-right layout, the leading corner is the component’s upper-left corner; the leading corner is the component’s upper-right corner for horizontal right-to-left layout. The default value assigned to gridx and gridy is constant GridBagConstraints.RELATIVE, which indicates that a component is placed immediately after (along the x axis for gridx; along the y axis for gridy) the component previously added to the container.
  • gridwidth and gridheight identify the number of cell columns and cell rows (respectively) in the component’s display area. The default value assigned to gridwidth and gridheight is 1. To indicate that the component’s display area ranges from gridx to the last cell in the row (gridwidth), or ranges from gridy to the last cell in the column (gridheight), assign constant GridBagConstraints.REMAINDER to the appropriate field. If you want to indicate that the component’s display area ranges from gridx to the next-to-last cell in its row (gridwidth), or ranges from gridy to the next-to-last cell in its column (gridheight), assign GridBagConstraints.RELATIVE to the appropriate field.
  • fill determines whether (and how) to resize the component when its display area is greater than its requested size. The following GridBagConstraints constants are the possible values that can be assigned to this field:
    • NONE tells GridBagLayout not to resize the component. This is the default.
    • HORIZONTAL makes the component wide enough to fill its display area horizontally, without changing its height.
    • VERTICAL makes the component tall enough to fill its display area vertically, without changing its width.
    • BOTH makes the component completely fill its display area.
  • ipadx and ipady identify the component’s internal padding—how much to add to the component’s minimum size—within the layout. The component’s width is at least ipadx*2 pixels because padding applies to both sides of the component. Similarly, the height is at least ipady*2 pixels. The default value assigned to both fields is 0.
  • insets identifies the component’s external padding—the minimum amount of space between the component and the edges of its display area. The value assigned to this field is specified as a java.awt.Insets object. By default, null is assigned to this field—there is no external padding.
  • anchor determines where to place a component within its display area when the component is smaller than that area. This field’s value is obtained from one of GridBagConstraints’ two sets of anchor constants. The older absolute constants correspond to the points on a compass: NORTH, SOUTH, WEST, EAST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST, and CENTER (the default). Unlike absolute anchor constants, which are not appropriate for localization, the relative anchor constants are interpreted relative to the container’s ComponentOrientation property: PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_START, and LAST_LINE_END.
  • The following diagram illustrates how the relative anchor constants are interpreted in a container that has the default left-to-right component orientation.
-------------------------------------------------
|FIRST_LINE_START PAGE_START  FIRST_LINE_END|
|            |
|            |
|LINE_START   CENTER    LINE_END|
|            |
|            |
|LAST_LINE_START  PAGE_END  LAST_LINE_END|
-------------------------------------------------
  • weightx and weighty specify how to distribute space among columns (weightx) and rows (weighty), which is important for specifying resizing behavior. GridBagLayout calculates the weight of a column to be the maximum weightx of all the components in a column. If the resulting layout is smaller horizontally than the area it needs to fill, the extra space is distributed to each column in proportion to its weight. A column with a 0.0 weight receives no extra space. Similarly, a row’s weight is calculated to be the maximum weighty of all the components in a row. If the resulting layout is smaller vertically than the area it needs to fill, the extra space is distributed to each row in proportion to its weight. A row with a 0.0 weight receives no extra space.

    Weights are positive real numbers ranging from 0.0 to (generally) 1.0: 0.0 is the default weight. When all components have 0.0 weights, they clump together in the container’s center.

GridBagLayout’s public GridBagLayout() constructor creates an instance of this class. After creating this object and establishing it as a container’s layout manager, one or more constraints objects are created by invoking the following GridBagConstraints constructors:

public GridBagConstraints()
public GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady)

The former GridBagConstraints() constructor creates a GridBagConstraints object with constraints fields (such as public int gridx) set to default values. You must assign values to these fields explicitly via separate assignment statements. In contrast, you can assign values to all fields in one step via the second constructor.

Although a separate GridBagConstraints object can be created for each component being managed by the GridBagLayout class, the same object can be associated with multiple components. (Before you associate this object with a component, you usually modify various fields to specify appropriate layout details for the component.) A component and its constraints object then can be added to a container, often by invoking java.awt.Container’s public void add(Component comp, Object constraints) method:

JPanel panel = new JPanel ();
panel.setLayout (new GridBagLayout ());
GridBagConstraints gbc = new GridBagConstraints ();

// ...

JButton button = new JButton ("Ok");
gbc.gridx = 1;
gbc.gridy = 1;
panel.add (button, gbc);

button = new JButton ("Cancel");
gbc.gridx = 2;
gbc.gridy = 1;
panel.add (button, gbc);

// ...

Behind the scenes (for J2SE 5.0, at least), the add(Component comp, Object constraints) method indirectly (and eventually) invokes the following GridBagLayout method to cache the component and its GridBagConstraints object in an internal hash table:

public void addLayoutComponent(Component comp, Object constraints)

The GridBagConstraints object is subsequently extracted from this hash table and used during a layout operation.

This method:

addLayoutComponent(Component comp, Object constraints)

invokes this GridBagLayout method to handle the caching:

public void setConstraints(Component comp, GridBagConstraints constraints)

Older application source code often explicitly invokes setConstraints() followed by Container’s public Component add(Component comp) method, which never invokes setConstraints(). In contrast to this older usage, I prefer the code fragment’s modern usage.

setConstraints(Component comp, GridBagConstraints constraints)

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020