0% found this document useful (0 votes)
23 views

Lesson No. 9 AWT SWING

Uploaded by

Christian Joshua
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Lesson No. 9 AWT SWING

Uploaded by

Christian Joshua
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

Object-Oriented Programming

Lesson No. 9

ABSTRACT WINDOWING TOOLKIT AND SWING

What is the lesson all about?

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.

What do you expect from the lesson?

After completing this lesson, you should be able to:


 Understand similarities and differences between AWT and Swing
 Differentiate between components and containers
 Design GUI applications using AWT
 Design GUI applications using Swing
 Describe how flow layout, border layout and grid layout position GUI components
 Create complex layouts in designing GUI appllications

What are the contents of the lesson?

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.

AWT GUI Components


Fundamental Window Classes
In developing GUI applications, the GUI components such as buttons or text fields are placed
in containers. These are the list of important container classes provided in the AWT.

AWT Class Description


Component An abstract class for objects that can be displayed on the console and
interact with the user. The root of all other AWT classes.
Container An abstract subclass of the Component class. A component that can contain
other components.
Panel Extends the Container class. A frame or window without the titlebar, the
menubar nor the border. Superclass of the Applet class.
Window Also extends Container class. A top-level window, which means that it
cannot be contained in any other object. Has no borders and no menubar.
Frame Extends the Window class. A window with a title, menubar, border, and
resizing corners. Has four constructors, two of which have the following
signatures:
Frame()
Frame(String title)

Table 1. AWT Container classes

To set the size of the window, the overloaded setSize method is used.
void setSize(int width, int height)

Resizes this component to the width and height provided as parameters.

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

public class SampleFrame extends Frame {


public static void main(String args[]) {
SampleFrame sf = new SampleFrame();
sf.setSize(300, 300); //Try removing this line
sf.setVisible(true); //Try removing this line
}
}

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.

drawLine() drawPolyline() setColor()


fillRect() drawPolygon() getFont()
drawRect() fillPolygon() setFont()
clearRect() getColor() drawString()
Table 2. Some methods of class Graphics

Related to this class is the Color class, which has three constructors.

Constructor Format Description


Color(int r, int g, int b) Integer value is from 0 to 255.
Color(float r, float g, float b) Float value is from 0.0 to 1.0.
Color(int rgbValue) Value range from 0 to 224-1 (black to white).
Red: bits 16-23
Green: bits 8-15
Blue: bits 0-7
Table 2b: Color constructors

Here is a sample program that uses some of the methods in the Graphics class.

import java.awt.*;

public class GraphicPanel extends Panel {


GraphicPanel() {
setBackground(Color.black);//constant in Color class
}
public void paint(Graphics g) {
g.setColor(new Color(0,255,0)); //green
g.setFont(new Font("Helvetica",Font.PLAIN,16));
g.drawString("Hello GUI World!", 30, 100);
g.setColor(new Color(1.0f,0,0)); //red
g.fillRect(30, 100, 150, 10);

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.

Figure 1. Output of sample code above

More AWT Components


Here is a list of AWT controls. Controls are components such as buttons or text fields that
allow the user to interact with a GUI application. These are all subclasses of the Component
class.

Label Button Choice


TextField Checkbox List
TextArea CheckboxGroup Scrollbar

Table 3. AWT Components

The following program creates a frame with controls contained in it.

import java.awt.*;

class FrameWControls extends Frame


{

juliomcervantes 163
Object-Oriented Programming

public static void main(String args[])


{
FrameWControls fwc = new FrameWControls();
fwc.setLayout(new FlowLayout());
fwc.setSize(600, 600);
fwc.add(new Button("Test Me!"));
fwc.add(new Label("Name"));
fwc.add(new TextField());
CheckboxGroup cbg = new CheckboxGroup();
fwc.add(new Checkbox("chk1", cbg, true));
fwc.add(new Checkbox("chk2", cbg, false));
fwc.add(new Checkbox("chk3", cbg, false));
List list = new List(3, false);
list.add("ABS-CBN");
list.add("GMA");
list.add("TV5");
fwc.add(list);
Choice chooser = new Choice();
chooser.add("Avril");
chooser.add("Monica");
chooser.add("Britney");
fwc.add(chooser);
fwc.add(new Scrollbar());
fwc.setVisible(true);
}
}

Shown below is a sample output.

Figure 2. Output of sample code above

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.

The FlowLayout Manager


The FlowLayout is the default manager for the Panel class and its subclasses, including the
Applet class. It positions the components in a left to right and top to bottom manner,
starting at the upper-lefthand corner. Imagine how you type using a particular word editor.
This is how the FlowLayout manager works.

It has three constructors which are as listed below.

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

alignment argument should be one of the following:


1. FlowLayout.LEFT
2. FlowLayout.CENTER
3. FlowLayout.RIGHT

What is the expected output of the following program?

import java.awt.*;

class FlowLayoutDemo extends Frame {


public static void main(String args[]) {
FlowLayoutDemo fld = new FlowLayoutDemo();
fld.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10));
fld.add(new Button("ONE"));
fld.add(new Button("TWO"));
fld.add(new Button("THREE"));
fld.setSize(100, 100);
fld.setVisible(true);
}
}

Shown below is a sample output.

Figure 3. Output of sample code in Windows

The BorderLayout Manager


The BorderLayout divides the Container into five parts- north, south, east, west and the
center. Each components is added to a specific region. The north and south regions stretch
horizontally whereas the east and west regions adjust vertically. The center region, on the
other hand, adjusts in both horizontally and vertically. This layout is the default for Window
objects, including objects of Window's subclasses Frame and Dialog type.

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

Table 5. BorderLayout constructors

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.*;

class BorderLayoutDemo extends Frame {


public static void main(String args[]) {
BorderLayoutDemo bld = new BorderLayoutDemo();
bld.setLayout(new BorderLayout(10, 10));//may remove
bld.add(new Button("NORTH"), BorderLayout.NORTH);
bld.add(new Button("SOUTH"), BorderLayout.SOUTH);
bld.add(new Button("EAST"), BorderLayout.EAST);
bld.add(new Button("WEST"), BorderLayout.WEST);
bld.add(new Button("CENTER"), BorderLayout.CENTER);
bld.setSize(200, 200);
bld.setVisible(true);
}
}

Here is a sample output of this program. The second figure shows the effect of resizing the
frame.

juliomcervantes 167
Object-Oriented Programming

Figure 4. Output of sample code

The GridLayout Manager


With the GridLayout manager, components are also positioned from left to right and top to
bottom as in the FlowLayout manager. In addition to this, the GridLayout manager divides
the container into a number of rows and columns. All these regions are equally sized. It
always ignores the component's preferred size.

The following is the available constructors for the GridLayout class.

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

Try out this program.

import java.awt.*;

class GridLayoutDemo extends Frame {


public static void main(String args[]) {
GridLayoutDemo gld = new GridLayoutDemo();
gld.setLayout(new GridLayout(2, 3, 4, 4));
gld.add(new Button("ONE"));
gld.add(new Button("TWO"));
gld.add(new Button("THREE"));
gld.add(new Button("FOUR"));
gld.add(new Button("FIVE"));
gld.setSize(200, 200);
gld.setVisible(true);
}
}

This is the output of the program. Observe the effect of resizing the frame.

juliomcervantes 168
Object-Oriented Programming

Figure 5. Output of sample code

Panels and Complex Layouts


To create more complex layouts, you can combine the different layout managers with the
use of panels. Remember that a Panel is a Container and a Component at the same time. You
can insert Components into the Panel and then add the Panel to a specified region in the
Container.

Observe the technique used in the following example.

import java.awt.*;

class ComplexLayout extends Frame {


public static void main(String args[]) {
ComplexLayout cl = new ComplexLayout();
Panel panelNorth = new Panel();
Panel panelCenter = new Panel();
Panel panelSouth = new Panel();
/* North Panel */
//Panels use FlowLayout by default
panelNorth.add(new Button("ONE"));
panelNorth.add(new Button("TWO"));
panelNorth.add(new Button("THREE"));
/* Center Panel */
panelCenter.setLayout(new GridLayout(4,4));
panelCenter.add(new TextField("1st"));
panelCenter.add(new TextField("2nd"));
panelCenter.add(new TextField("3rd"));
panelCenter.add(new TextField("4th"));
/* South Panel */
panelSouth.setLayout(new BorderLayout());
panelSouth.add(new Checkbox("Choose me!"), BorderLayout.CENTER);
panelSouth.add(new Checkbox("I'm here!"), BorderLayout.EAST);
panelSouth.add(new Checkbox("Pick me!"), BorderLayout.WEST);

juliomcervantes 169
Object-Oriented Programming

/* Adding the Panels to the Frame container */


//Frames use BorderLayout by default
cl.add(panelNorth, BorderLayout.NORTH);
cl.add(panelCenter, BorderLayout.CENTER);
cl.add(panelSouth, BorderLayout.SOUTH);
cl.setSize(300,300);
cl.setVisible(true);
}
}

Here is the output of the program.

Figure 6. Output of sample code

Swing GUI Components


Like the AWT package, the Swing package provides classes for creating GUI applications. The
package is found in javax.swing. The main difference between these two is that Swing
components are written entirely using Java whereas the latter is not. As a result, GUI
programs written using classes from the Swing package have the same look and feel even
when executed on different platforms. Moreover, Swing provides more interesting
components such as the color chooser and the option pane.

The names of the Swing GUI components are almost similar to that of the AWT GUI

juliomcervantes 170
Object-Oriented Programming

components. An obvious difference is in the naming conventions of the components.


Basically, the name of Swing components are just the name of AWT components but with an
additional prefix of J. For example, one component in AWT is the Button class. The
corresponding component for this in the Swing package is the JButton class. Provided below
is the list of some of the Swing GUI components.

Swing Component Description


JComponent The root class for all Swing components, excluding top-level
containers.
JButton A "push" button. Corresponds to the Button class in the AWT package.
JCheckBox An item that can be selected or deselected by the user. Corresponds to
the Checkbox class in the AWT package.
JFileChooser Allows user to select a file. Corresponds to the FileChooser class in the
AWT package.
JTextField Allows for editing of a single-line text. Corresponds to TextField
class in the AWT package.
JFrame Extends and corresponds to the Frame class in the AWT package
but the two are slightly incompatible in terms of adding components
to this container. Need to get the current content pane before
adding a component.
JPanel Extends JComponent. A simple container class but not top-level.
Corresponds to Panel class in the AWT package.
JApplet Extends and corresponds to the Applet class in the AWT package.
Also slightly incompatible with the Applet class in terms of adding
components to this container.
JOptionPane Extends JComponent. Provides an easy way of displaying pop-up
dialog box.
JDialog Extends and corresponds to the Dialog class in the AWT package.
Usually used to inform the user of something or prompt the user for
an input.
JColorChooser Extends JComponent. Allow the user to select a color.

Table 7. Some Swing components

For the complete list of Swing components, please refer to the API documentation.

Setting Up Top-Level Containers


As mentioned, the top-level containers like JFrame and JApplet in Swing are slightly
incompatible with those in AWT. This is in terms of adding components to the container.
Instead of directly adding a component to the container as in AWT containers, you have to
first get the content pane of the container. To do this, you'll have to use the getContentPane
method of the container.

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.

Here is a sample output.

juliomcervantes 172
Object-Oriented Programming

Figure 7. Output of sample code

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();
}
}

See how easy it is ask input from the user.


Here is the sample output for the given program.

Figure 8. Output of sample code

juliomcervantes 173
Object-Oriented Programming

Name: _________________________________________________________________
Year & Section:___________________________ Date ___________________________

SKILLS WARM-UP

True or False. Write your answer in the space provided.

_______ 1. The GridLayout manager arranges GUI components in a list formation.

_______ 2. The class JComponent is part of the package javax.swing.

_______ 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.

_______ 6. JFrame is a class.

_______ 7. The class JFrame contains the method setSize.

_______ 8. In Java, extends is a reserved word.

_______ 9. You cannot create a window by using an object of type JFrame.

_______ 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.

1. Which of the following is NOT a required attribute of a window?


a. title c. height
b. width d. color
2. The Java class that you use to create windows is ____.
a. JTextField c. JButton
b. Jframe d. JLabel

3. Which of the following methods is NOT part of the class JFrame?


a. setVisible c. setTitle
b. setSize d. getText

4. To create a window, which of the following classes has to be extended?


a. Container c. JButton
b. JFrame d. JTextField

5. Which of the following is a reserved word in Java?


a. extends c. event
b. pane d. inheritance

6. To display a window, you must invoke the method ____.


a. displayWindow c. setVisible
b. show d. setDisplay

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.

Figure 1.5.1: Tic-Tac-Toe board

juliomcervantes 177

You might also like