Digital Edition

Lesson 12: An Introduction to Graphical User Interfaces with Swing - Part I
Everything is a little better, faster, and more convenient in Swing

Box Layout
Class java.swing.BoxLayout allows multiple window components to be laid out either horizontally (along the X-axis) or vertically (along the Y-axis). Unlike with the FlowLayout manager, when the window with the BoxLayout is resized, its controls are not getting wrapped up. With BoxLayout, window controls can have different sizes (this is not allowed in the GridLayout).

The next two lines of code set a box layout with vertical alignment in a JPanel.

JPanel p1= new JPanel();
setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));

To make this code shorter, I do not declare a variable to store a reference to the object BoxLayout, but rather create an instance of this object and immediately pass it to the method setLayout() as an argument.

Grid Bag Layout
In this section I'll show you yet another way of creating the calculator window using java.awt.GridBagLayout manager instead of combining layouts and panels.

Our calculator has rows and columns, but in a grid layout, all of the components must have the same size. This does not work for our calculator because there is a text field on the top that is as wide as tree numeric buttons.

The GridBagLayout is an advanced grid, that allows you to have a grid with cells of different sizes. Class GridBagLayout works together with another class called GridBagConstraints. Constrains is nothing else but attributes of the cell, and you have to set them for each cell separately. All constraints for a cell have to be set before placing a component in the cell. For example, one of the constraint's attributes is called gridwidth. It allows you to make a cell as wide as several other cells.

When working with the grid layout you should create an instance of the constraint object first, and then set the values to its properties. After this is done, you can add the component to the cell in your container.

The next code sample is heavily sprinkled with comments to help you understand how to use GridBagLayout.

// Set the GridBagLayout for the window's content pane
GridBagLayout gb = new GridBagLayout();

// Create an instance of the GridBagConstraints
// You'll have to repeat these lines for each component
// that you'd like to add to the grid cell
GridBagConstraints constr = new GridBagConstraints();

//setting constraints for the Calculator's displayField:

// x coordinate in the grid
// y coordinate in the grid

// this cell has the same height as other cells
constr.gridheight =1;

// this cell is as wide as 6 other ones
constr.gridwidth= 6;

// fill all space in the cell
constr.fill= constr.BOTH;
// proportion of horizontal space taken by this
// component
constr.weightx = 1.0;

// proportion of vertical space taken by this component
constr.weighty = 1.0;
// position of the component within the cell

displayField = new JTextField();
// set constrains for this field

// add the text field to the window
Spring Layout
The spring layout is based on the principles of actual springs and struts. Imagine that you have a bunch of hooks, springs and struts and need to fix our buttons and text fields to the edges of the window. Components that are attached with struts, won't move and change size if you start stretching the window, but those with springs can grow.

The distances between the components are defined by spring's properties (minimum, maximum, preferred and actual size). These parameters are specified in the SpringLayout.Constraints object for each component. This makes it somewhat similar to the GridBagLayout.

As opposed to GridLayout, SpringLayout allows you to arrange components of different sizes but maintain their relative positions.

You can read more on this layout in the article by Joe Winchester "SpringLayout: A Powerful and Extensible Layout Manager" ( ).

Card Layout
Think of a deck of cards laying on top of each other, where you can only see the top card. The java.awt.CardLayout manager can be used if you need to create a component that looks like a tab folder.

When you click on a tab, the content of the screen changes. In fact, all of the panels needed for this screen are already pre-loaded and lay on top of each other. When the user clicks on a tab, the program just "brings this card" on top and makes the rest of the cards invisible.

About Yakov Fain
Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs ( and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

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

Register | Sign-in

Reader Feedback: Page 1 of 1

Subscribe to the World's Most Powerful Newsletters


Having been in the web hosting industry since 2002, dhosting has gained a great deal of experience w...
NanoVMs is the only production ready unikernel infrastructure solution on the market today. Unikerne...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the m...
SUSE is a German-based, multinational, open-source software company that develops and sells Linux pr...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are rep...
Technological progress can be expressed as layers of abstraction - higher layers are built on top of...
When building large, cloud-based applications that operate at a high scale, it’s important to mainta...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, disc...
Big Switch's mission is to disrupt the status quo of networking with order of magnitude improvements...
Lori MacVittie is a subject matter expert on emerging technology responsible for outbound evangelism...
Dynatrace is an application performance management software company with products for the informatio...
In his session at 21st Cloud Expo, Michael Burley, a Senior Business Development Executive in IT Ser...
All in Mobile is a mobile app agency that helps enterprise companies and next generation startups bu...
Yottabyte is a software-defined data center (SDDC) company headquartered in Bloomfield Township, Oak...
Serveless Architectures brings the ability to independently scale, deploy and heal based on workload...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it wil...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the c...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical ...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (No...
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in developm...