Lesson No. 9 AWT SWING
Lesson No. 9 AWT SWING
Lesson No. 9
In this lesson, we will be discussing about graphical user interface (GUI). Without learning
about GUI Application Program Interfaces (APIs), you would still be able to create quite a
descent range of different programs. However, your applications are very likely to be bland
and unappealing to the users. Having a good GUI affects the usage of your application. This
results in ease of use and enjoyment of use for the users of your program. Java provides
tools like Abstract Windowing Toolkit (AWT) and Swing to develop interactive GUI
applications.
The Java Foundation Classes (JFCs), which is an important part of the Java SDK, refers to a
collection of APIs that simplifies the development Java GUI applications. It primarily consists
of five APIs including AWT and Swing. The three other APIs are Java2D, Accessibility, and
Drag and Drop. All these APIs assist developers in designing and implementing visually-
enhanced applications.
Both AWT and Swing provides GUI components that can be used in creating Java
applications and applets. You will learn about applets in a latter section. Unlike some AWT
components that use native code, Swing is written entirely using the Java programming
language. As a result, Swing provides a platform-independent implementation ensuring that
juliomcervantes 160
Object-Oriented Programming
applications deployed across different platforms have the same appearance. AWT, however,
does ensure that the look and feel of an application run on two different machines be
comparable. The Swing API is built around a number of APIs that implement various parts of
the AWT. As a result, AWT components can still be used with Swing components.
To set the size of the window, the overloaded setSize method is used.
void setSize(int width, int height)
void setSize(Dimension d)
Resizes this component to d.width and d.height based on the Dimension d specified.
A window by default is not visible unless you set its visibility to true. Here is the syntax for
the setVisible method.
void setVisible(boolean b)
In designing GUI applications, Frame objects are usually used. Here's an example of how to
create such an application.
import java.awt.*;
juliomcervantes 161
Object-Oriented Programming
Note that the close button of the frame doesn't work yet because no event handling
mechanism has been added to the program yet. You'll learn about event handling in the next
module.
Graphics
Several graphics method are found in the Graphics class. Here is the list of some of these
methods.
Related to this class is the Color class, which has three constructors.
Here is a sample program that uses some of the methods in the Graphics class.
import java.awt.*;
juliomcervantes 162
Object-Oriented Programming
}
public static void main(String args[]) {
Frame f = new Frame("Testing Graphics Panel");
GraphicPanel gp = new GraphicPanel();
f.add(gp);
f.setSize(500, 300);
f.setVisible(true);
}
}
For a panel to become visible, it should be placed inside a visible window like a frame.
import java.awt.*;
juliomcervantes 163
Object-Oriented Programming
Layout Managers
The position and size of the components within each container is determined by the layout
juliomcervantes 164
Object-Oriented Programming
manager. The layout managers governs the layout of the components in the container.
These are some of the layout managers included in Java.
1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. CardLayout
The layout manager can be set using the setLayout method of the Container class. The
method has the following signature.
void setLayout(LayoutManager mgr)
If you prefer not to use any layout manager at all, you pass null as an argument to this
method. But then, you would have to position the elements manually with the use of the
setBounds method of the Component class.
public void setBounds(int x, int y, int width, int height)
The method controls the position based on the arguments x and y, and the size based on the
specified width and height. This would be quite difficult and tedious to program if you have
several Component objects within the Container object. You'll have to call this method for
each component.
In this section, you'll learn about the first three layout managers.
FlowLayout Constructors
FlowLayout()
Creates a new FlowLayout object with the center alignment and 5-unit horizontal and
vertical gap applied to the components by default.
FlowLayout(int align)
Creates a new FlowLayout object with the specified alignment and the default 5-unit
horizontal and vertical gap applied to the components.
FlowLayout(int align, int hgap, int vgap)
Creates a new FlowLayout object with the first argument as the alignment applied and the
hgap-unit horizontal and vgap-unit vertical gap applied to the components.
Table 4. FlowLayout constructors
The gap refers to the spacing between the components and is measured in pixels. The
juliomcervantes 165
Object-Oriented Programming
import java.awt.*;
BorderLayout Constructors
BorderLayout()
Creates a new BorderLayout object with no spacing applied among the different
components.
BorderLayout(int hgap, int vgap)
Creates a new BorderLayout object with hgap-unit horizontal and vgap-unit spacing
applied among the different components.
juliomcervantes 166
Object-Oriented Programming
Like in the FlowLayout manager, the parameters hgap and vgap here also refers to the
spacing between the components within the container.
To add a component to a specified region, use the add method and pass two arguments: the
component to add and the region where the component is to be positioned. Note that only
one component can be placed in one region. Adding more than one component to a
particular container results in displaying only the last component added. The following list
gives the valid regions are predefined fields in the BorderLayout class.
1. BorderLayout.NORTH
2. BorderLayout.SOUTH
3. BorderLayout.EAST
4. BorderLayout.WEST
5. BorderLayout.CENTER
Here is a sample program demonstrating how the BorderLayout works.
import java.awt.*;
Here is a sample output of this program. The second figure shows the effect of resizing the
frame.
juliomcervantes 167
Object-Oriented Programming
GridLayout Constructors
GridLayout()
Creates a new GridLayout object with a single row and a single column by default.
GridLayout(int rows, int cols)
Creates a new GridLayout object with the specified number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap)
Creates a new GridLayout object with the specified number of rows and columns. hgap-
unit horizontal and vgap-unit vertical spacings are applied to the components.
Table 6. GridLayout constructors
import java.awt.*;
This is the output of the program. Observe the effect of resizing the frame.
juliomcervantes 168
Object-Oriented Programming
import java.awt.*;
juliomcervantes 169
Object-Oriented Programming
The names of the Swing GUI components are almost similar to that of the AWT GUI
juliomcervantes 170
Object-Oriented Programming
For the complete list of Swing components, please refer to the API documentation.
juliomcervantes 171
Object-Oriented Programming
A JFrame Example
import javax.swing.*;
import java.awt.*;
class SwingDemo {
JFrame frame;
JPanel panel;
JTextField textField;
JButton button;
Container contentPane;
void launchFrame() {
/* initialization */
frame = new JFrame("My First Swing Application");
panel = new JPanel();
textField = new JTextField("Default text");
button = new JButton("Click me!");
contentPane = frame.getContentPane();
/* add components to panel– uses FlowLayout by default */
panel.add(textField);
panel.add(button);
/* add components to contentPane– uses BorderLayout */
contentPane.add(panel, BorderLayout.CENTER);
frame.pack();
//causes size of frame to be based on the components
frame.setVisible(true);
}
public static void main(String args[]) {
SwingDemo sd = new SwingDemo();
sd.launchFrame();
}
}
Note that the java.awt package is still imported because the layout managers in use are
defined in this package. Also, giving a title to the frame and packing the components within
the frame is applicable for AWT frames too.
Coding Guidelines:
Observe the coding style applied in this example as opposed to the examples for AWT. The
components are declared as fields, a launchFrame method is defined, and initialization and
addition of components are all done in the launchFrame method. We no longer just extend
the Frame class. The advantage of using this style would become apparent when we get to
event handling.
juliomcervantes 172
Object-Oriented Programming
A JOptionPane Example
import javax.swing.*;
class JOptionPaneDemo {
JOptionPane optionPane;
void launchFrame() {
optionPane = new JOptionPane();
String name = optionPane.showInputDialog("Hi,what's your name?");
optionPane.showMessageDialog(null,
"Nice to meet you, " + name + ".", "Greeting...",
optionPane.PLAIN_MESSAGE);
System.exit(0);
}
public static void main(String args[]) {
new JOptionPaneDemo().launchFrame();
}
}
juliomcervantes 173
Object-Oriented Programming
Name: _________________________________________________________________
Year & Section:___________________________ Date ___________________________
SKILLS WARM-UP
_______ 3. The class Container is the superclass of all the classes designed to provide a GUI.
_______ 4. The layout manager FlowLayout places components in the container from left to
right and centered, by default, until no more items can be placed.
_______ 5. When you use BorderLayout, you are required to add components into each of
the five regions.
_______ 10. The class Container provides the method setLayout to set the layout of the
content pane.
juliomcervantes 174
Object-Oriented Programming
Name: _________________________________________________________________
Year & Section:___________________________ Date ___________________________
SKILLS WORKOUT
Multiple Choice: Encircle the letter that corresponds to the correct answer.
7. Which of the following sets the window width to 100 pixels and the height to 200 pixels?
a. setSize(100, 200); c. setDims(100, 200);
b. setSize(200, 100); d. set(200, 100);
8. Use the ____ layout manager when you add components to a maximum of five sections.
a. BorderLayout c. GridBagLayout
b. GridLayout d. CardLayout
9. Which of the following is the default layout manager for a Java application?
a. null c. FlowLayout
b. GridLayout d. BorderLayout
10. In which of the following layout managers do all rows (columns) have the same number
of components and all components have the same size?
a. GridLayout c. BorderLayout
juliomcervantes 175
Object-Oriented Programming
b. FlowLayout d. EvenLayout
Name: _________________________________________________________________
Year & Section:___________________________ Date ___________________________
Hands-on Activity
juliomcervantes 176
Object-Oriented Programming
Tic-Tac-Toe
Create the GUI interface for a Tic-Tac-Toe program. The board consists of nine squares. Keep
in mind that you'll be enhancing this code later on to handle user interaction. So, design your
board wisely. Make sure you choose the appropriate components for the board. Feel free to
unleash your artistic side. :) You may either use AWT or Swing for this exercise.
juliomcervantes 177