Digital Edition

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

This may not be the best-looking calculator, but it'll give us a chance to learn how to add components and display a window. In the next section we'll try make it look better with the help of layout managers.

Layout Managers
Some old-fashioned programming languages force you to set exact coordinates and sizes of each window component. This works fine if you know the screen settings (resolution) of all users of your program. Java has layout managers that help you arrange components on the screen without assigning strict positions to the window controls. Layout managers will ensure that their screen will look nice regardless of the window size.

Swing offers the following layout managers:

  • FlowLayout
  • GridLayout
  • BoxLayout
  • BorderLayout
  • CardLayout
  • SpringLayout
  • GridBagLayout
To use any layout manager, a program needs to instantiate it, and then assign this object to a container , for example to a panel as in the class SimpleCalculator.

Flow Layout
This layout arranges components in a window row by row. For example, labels, text fields and buttons will be added to the first imaginary row until there is room there. When the current row is filled, the rest of the components will go to the next row, and so on. If a user changes the size of the window, it may mess up the picture. Just grab the corner of our calculator window and resize it. Watch how the manager java.awt.FlowLayout rearranges controls as the size of the window changes.


In the next code sample, the keyword this represents an instance of the object SimpleCalculator.

FlowLayout fl = new FlowLayout();
this.setLayoutManager(fl);

Well, the FlowLayout is not the best choice for our calculator. Let's try something different now.

Grid Layout
The class java.awt.GridLayout allows you to arrange components as rows and columns in a grid. You'll be adding components to imaginary cells of this grid. If the screen gets resized, grid cells may become bigger, but the relative positions of window components will stay the same. Our calculator has seven components - three labels, three text fields and a button. We may arrange them as a grid of four rows and two columns (one cell stays empty):

GridLayout gr = new GridLayout(4,2);

You can also assign some horizontal and vertical space gaps between the cells, for example five pixels:

GridLayout gr = new GridLayout(4,2,5,5);

After minor changes in our calculator (they are highlighted below), our calculator will look a lot prettier. Create and compile a new class SimpleCalculatorGrid in the project My Calculator.


import javax.swing.*;
import java.awt.GridLayout;

public class SimpleCalculatorGrid {
public static void main(String[] args) {
// Create a panel
JPanel windowContent= new JPanel();

// Set the layout manager for this panel
GridLayout gl = new GridLayout(4,2);
windowContent.setLayout(gl);

// Create controls in memory

JLabel label1 = new JLabel("Number 1:");
JTextField field1 = new JTextField(10);
JLabel label2 = new JLabel("Number 2:");
JTextField field2 = new JTextField(10);
JLabel label3 = new JLabel("Sum:");
JTextField result = new JTextField(10);
JButton go = new JButton("Add");

// Add controls to the panel
windowContent.add(label1);
windowContent.add(field1);
windowContent.add(label2);
windowContent.add(field2);
windowContent.add(label3);
windowContent.add(result);
windowContent.add(go);

// Create the frame and add the panel to it
JFrame frame = new JFrame(
"My First Calculator");
frame.setContentPane(windowContent);

// set the size and display the window
//frame.pack();
frame.setSize(400,100);
frame.setVisible(true);
}
}
Run the program SimpleCalculatorGrid, and you'll see this window:


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 (http://yakovfain.com) 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



ADS BY GOOGLE
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE

Consumer-driven contracts are an essential part of a mature microservice testing portfolio enabling ...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitori...
Adding public cloud resources to an existing application can be a daunting process. The tools that y...
Using new techniques of information modeling, indexing, and processing, new cloud-based systems can ...
A valuable conference experience generates new contacts, sales leads, potential strategic partners a...
Containers and Kubernetes allow for code portability across on-premise VMs, bare metal, or multiple ...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use ...
SYS-CON Events announced today that Silicon India has been named “Media Sponsor” of SYS-CON's 21st I...
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 20...
In this presentation, you will learn first hand what works and what doesn't while architecting and d...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22n...
Everyone wants the rainbow - reduced IT costs, scalability, continuity, flexibility, manageability, ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 1...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, wi...
Most DevOps journeys involve several phases of maturity. Research shows that the inflection point wh...
Andi Mann, Chief Technology Advocate at Splunk, is an accomplished digital business executive with e...
Today, we have more data to manage than ever. We also have better algorithms that help us access our...
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by Fi...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: D...