0% found this document useful (0 votes)
19 views83 pages

CH 1

Java course material

Uploaded by

temesgen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views83 pages

CH 1

Java course material

Uploaded by

temesgen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Wolaita Sodo University

School of Informatics
Department of Computer Science

Advanced Programming

1
Chapter-1
AWT and Swing

By the end of this chapter, you will be able:


• To create and manipulate buttons, labels, lists, text fields, panels, sliders, menus and
pop-up menus .

• To use layout managers to arrange GUI components.

• To build GUIs and handle events generated by user interactions with GUIs.

• To understand the packages containing GUI components, event-handling classes


and interfaces.

• To handle mouse events and keyboard events.

2
Chapter-1
AWT and Swing

AWT vs SWING
GUI, which stands for Graphical User Interface, refers to that portion of a program that
the user visually sees and interacts with.

A graphical user interface (GUI) presents a user-friendly mechanism for interacting


with an application.

GUIs are built from GUI components. These are sometimes called controls or widgets.

Providing different applications with consistent, intuitive user-interface components


gives users a sense of familiarity with a new application, so that they can learn it more
quickly and use it more productively.

When Java was first released in 1995, it contained a GUI API referred to as the Abstract
Windowing Toolkit (AWT).
This API contained classes like Frame to represent a typical window, Button to
represent buttons, Menu to represent a window’s menu, and so on.
The classes and interfaces of the AWT are in the java.awt packages.
3
Chapter-1
AWT and Swing

Although it is a useful and important API, the AWT had its shortcomings, including;

AWT components are referred to as heavyweight components because their


implementation relies heavily on the underlying operating system.

The look and feel of AWT components depend on the platform the program is running
on.
For example, an AWT button will look like a Windows button when the program is run
on a Windows platform. The same button will look like a Macintosh button when the
program is run on a Macintosh platform.

a lack of support for many popular GUI components


User interface elements such as menus, scrollbars, and text fields can have subtle
differences in behavior on different platforms.

GUI applications built with the AWT simply did not look as nice as native Windows or
Macintosh applications, nor did they have the kind of functionality that users of those
platforms had come to expect.
More depressingly, there were different bugs in the AWT user interface library on the
4
different platforms.
Chapter-1
AWT and Swing

Sun worked with Netscape to create a user interface library with the code name
“Swing.”

Swing was available as an extension to Java 1.1 and became a part of the standard
library in Java SE 1.2.

Swing is actually a part of the Java Foundation Classes (JFC), a collection of


technologies that includes Swing, AWT, Java 2D, Java Drag and Drop, the Accessibility
APIs, and others.

The classes and interfaces of Swing are found in the javax.swing packages.

Swing components are referred to as lightweight components because their


implementation does not rely on the underlying operating system.

NOTE:
Swing is not a complete replacement for the AWT—it is built on top of the AWT
architecture.
Swing simply gives you more capable user interface components.
You use the foundations of the AWT, in particular, event handling, whenever you write a
Swing program.

5
Chapter-1
AWT and Swing

The names of the Swing classes all begin with a capital J, like JButton.

For the most part, an AWT program can be converted to a Swing program by adding a
capital J to the class names used in the source code and recompiling the code.

NOTE: Most Java user interface programming is nowadays done in Swing, with one
notable exception.
The Eclipse integrated development environment uses a graphics toolkit called SWT
that is similar to the AWT, mapping to native components on various platforms.
You can find articles describing SWT at http://www.eclipse.org/articles/.

Show more

Creating Windows
A top-level window (that is, a window that is not contained inside another window) is
called a frame in Java.

The AWT library has a class, called Frame, for this top level.

6
The Swing version of this class is called JFrame and extends the Frame class.
Chapter-1
AWT and Swing

Basic Swing GUI components

7
Chapter-1
AWT and Swing

CAUTION:
Most Swing component classes start with a “J”: JButton, JFrame, and so on.
There are classes such as Button and Frame, but they are AWT components.

If you accidentally omit a “J”, your program may still compile and run, but the mixture of
Swing and AWT components can lead to visual and behavioral inconsistencies.

When working with Frame objects, there are basically three steps involved to get a
Frame window to appear on the screen:

1. Instantiate the Frame object in memory.


2. Give the Frame object a size using setSize(), setBounds(), or pack().
3. Make the Frame appear on the screen by invoking setVisible(true).

. Let’s look at instantiating a Frame object first. The java.awt.Frame class has four
constructors:

public Frame(). Creates a new frame with no message in the title bar.

public Frame(String title). Creates a new frame with the given String appearing in the
title bar

8
Chapter-1
AWT and Swing

public Frame(GraphicsConfiguration gc). Creates a frame with the specified


GraphicsConfiguration of a screen device.

public Frame(String title, GraphicsConfiguration gc). Creates a frame with


the specified title and GraphicsConfiguration.

The following statement demonstrates instantiating a new Frame object in


memory:
Frame f = new Frame(“My first window”);

This Frame is not displayed on the screen, and it has an initial size of 0 by 0.
You need to give your Frame a size before displaying it, which can be done
by invoking one of the following methods

public void setSize(int width, int height). Sets the size of the
Frame to the given width and height, in pixels.

public void setSize(java.awt.Dimension d). Sets the size of the Frame


to the same width and height as the given Dimension object. 9
Chapter-1
AWT and Swing

public void setBounds(int x, int y, int width, int height). Sets


both the size and initial location of the window, where x represents the
number of pixels over from the upper-left corner of the screen, and y
represents the number of pixels down from the upper-left corner of the
screen.

public void pack(). Sets the size of the Frame to be just big enough to
display all its components with their preferred size

I recommend students invoking more than one of the setSize(), setBounds(),


or pack() methods to set the size of a window. However, you need to invoke
only one of them.

After you have instantiated a Frame, given it a size, and laid out the
components within it, you display the Frame on the screen by invoking the
setVisible() method inherited from the Component class.
The signature of setVisible() is:

public void setVisible(boolean show)

If the boolean passed in is true, the component is made visible. If the value
is false, the component is hidden.
10
Chapter-1
AWT and Swing

For example, the following program displays the frame/window shown below
import java.awt.*;
public class FrameDemo
{
public static void main(String [] args)
{
Frame f = new Frame("My first window");
f.setBounds(100,100, 400, 300);
f.setVisible(true);
}
} You can move, resize, minimize, and
maximize
the Frame window. However, you can’t
close the window because closing a
window often implies ending the
program.

If the user needs to save a document or


other settings before ending, your
program needs a chance to do this.

11
Chapter-1
AWT and Swing

Example 2

import javax.swing.*;
public class JavaApplication1
{
public static void main(String [] args)
{

JFrame f = new JFrame("My first JFrame");


f.setSize(400, 300);

f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);

To exit the program, we use the statement;


}
} frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The package name javax indicates a Java extension package, not a core
12
package.
Chapter-1
AWT and Swing

Example 3
import javax.swing.*;
public class JavaApplication1
{
public static void main(String [] args)
{

SimpleFrame frame = new SimpleFrame();


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class SimpleFrame extends JFrame


{
public SimpleFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle(MYTITLE);
}

public static final int DEFAULT_WIDTH = 300;


public static final int DEFAULT_HEIGHT = 200;
public static final String MYTITLE="My Second JFrame"; 13
}
Chapter-1
AWT and Swing

you can set a JFrame’s look and feel using the setDefaultLookAndFeelDecorated() method.

Example
import javax.swing.*;
public class JFrame2
{
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame aFrame = new JFrame("Second frame");
aFrame.setSize(250, 100);
aFrame.setVisible(true);
}
}

14
Chapter-1
AWT and Swing

Clicking the X in the title bar of a JFrame causes the window to be


hidden by default, but this does not cause your program to stop
executing.

As with Frame objects, you can handle the WindowEvent of the


Jframe and use the System.exit() method to stop execution of the
program.

However, unlike the Frame class, the JFrame class contains a


setDefaultCloseOperation() method that allows you to decide
what action to take when the user closes the JFrame.

The method takes in an int, which can be one of the following


values:
WindowConstants.HIDE_ON_CLOSE. Hides the JFrame. This is the
default behavior.

WindowConstants.DO_NOTHING_ON_CLOSE. Does nothing, which is


similar to the behavior of Frame objects.

WindowConstants.DISPOSE_ON_CLOSE. Hides and disposes the 15


Chapter-1
AWT and Swing

The setResizable method, which takes a boolean to determine if a frame will be


resizeable by the user

To find out the screen size, use the following steps.

Call the static getDefaultToolkit method of the Toolkit class to get the
Toolkit object.
Then call the getScreenSize method, which returns the screen size as a
Dimension object.

Jframe consists of the following important methods in addition to the


methods listed above;

The setIconImage method, which tells the windowing system which


icon to display in the title bar, task switcher window, and so on

Because the representation of images is also system dependent, we again use the
toolkit to load an image. Then, we set the image as the icon for the frame:

Image img = kit.getImage("icon.gif"); 16


setIconImage(img);
Chapter-1
AWT and Swing

The setLocationByPlatform(boolean b) method define the locationByPlatform property:


Example 4
import java.awt.*; class SizedFrame extends JFrame
{
import javax.swing.*; public SizedFrame()
public class {
JavaApplication1 // get screen dimensions
{ Toolkit kit =
public static void Toolkit.getDefaultToolkit();
Dimension screenSize =
main(String [] args) kit.getScreenSize();
{ int screenHeight =
screenSize.height;
int screenWidth = screenSize.width;
SizedFrame frame = new
// set frame width, height and
SizedFrame(); let platform pick screen location
setSize(screenWidth / 2,
frame.setDefaultCloseOperat screenHeight / 2);
ion(JFrame.EXIT_ON_CLOSE); setLocationByPlatform(true);
// set frame icon and title
frame.setVisible(true); Image img =
kit.getImage("twitter.png");
} setIconImage(img);
} setTitle("SizedFrame");
}
}
17
Chapter-1
AWT and Swing

Inheritance hierarchy for the frame and component classes in AWT and Swing

Back

18
Chapter-1
AWT and Swing

Containers and Components


There are two basic elements of a GUI: containers and components.
A container is for displaying components, and components must be displayed
within a container.

A Button is an example of a component, whereas a Frame is an example of a


container.
To display a Button, you place it within a Frame and display the Frame.

Component is an abstract class that is the parent class of the various GUI
components of the AWT: Button, Checkbox, Choice, Label, List, and Text
Component.

Container is an abstract class that is the parent class of the containers of the
AWT: Window, Panel, and ScrollPane.
Child objects of Component are placed within child objects of Container.

For example, a Button can be placed within a Panel, or a List can be placed
within a Frame.
19
Chapter-1
AWT and Swing

Containers and Components

Components are placed inside containers. However, notice that Container is a child of
Component. Therefore, a container is a component, which allows a Container object to
be placed inside another Container object.

For example, a Panel is a Container, and a Frame is a Container. Because Panel is


also a Component, a Panel can be placed inside a Frame. (Using the same logic, a
Frame can also be placed inside a Panel.)

The JComponent class is a child of Container, and it is the parent class of all of the
Swing components, such as JComboBox, JLabel, JSlider, JSpinner, and JMenuBar.

One of the ways that Swing is different from AWT is that not all AWT components are
containers. However, all Swing components extend JComponent, which extends
Container.

Therefore, all Swing components are also containers, allowing them to be nested within
each other.
For example, a JButton can be placed within a JFrame (a typical use of JButton).

However, because JButton is a child of Container, you can place a JFrame inside a
JButton
(which is not a typical GUI feature, but nonetheless this can be done in Swing).
20
Chapter-1
AWT and Swing

Adding Components to a Container


A Component is added to a Container using one of the following add() methods found in
the java.awt.Container class:

public Component add(Component c). Adds the Component to the Container and
returns a reference to the newly added Component

public Component add(Component c, int index). Adds the Component to the Container
at the position specified by index

public Component add(Component c, Object constraints). Adds the Component to the


Container using the specified constraints

Which add() method you use depends on which layout manager you are using.

Components are added to a JFrame differently from the way they are added to a
Frame.

When using a Frame, you invoke the add() method directly on the Frame object, adding
the components directly to the Frame.

21
Chapter-1
AWT and Swing

Adding Components to a Container

When using a JFrame, you still invoke the add() method, but not on the
JFrame. Instead, you add the components to the content pane of the JFrame
by invoking the add() method on the JFrame’s content pane.

You use the getContentPane() method in the JFrame class to obtain a


reference to the content pane of a JFrame.

For example, the following statements add a JButton to the content pane of a
JFrame:

JFrame f = new JFrame();


JButton b = new JButton();
Container contentPane = f.getContentPane();
contentPane.add(b);

Notice that the return value of getContentPane() is Container.


The add() method is invoked on the content pane, adding b by using the layout
manager of the content pane.

22
Chapter-1
AWT and Swing

Using the JLabel Class


JLabel is a built-in Java Swing class that holds text you can display.

The inheritance hierarchy of the JLabel class is shown in the figure below

Available constructors for the JLabel class include the following:

JLabel() creates a JLabel instance with no image and with an empty string for
the title.

JLabel(Icon image) creates a JLabel instance with the specified image.

23
Chapter-1
AWT and Swing

JLabel(Icon image, int horizontalAlignment) creates a JLabel


instance with the specified image and horizontal alignment.

JLabel(String text) creates a JLabel instance with the specified


text.

JLabel(String text, Icon icon, int horizontalAlignment) creates a


Jlabel instance with the specified text, image, and horizontal
alignment.

JLabel(String text, int horizontalAlignment) creates a JLabel


instance with the specified text and horizontal alignment

24
Chapter-1
AWT and Swing

Example
import java.awt.*;
import javax.swing.*;
public class JFrame2
{
public static void main(String[] args)
{
final int FRAME_WIDTH = 250;
final int FRAME_HEIGHT = 100;
JFrame aFrame = new JFrame("Third frame");
aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
aFrame.setVisible(true);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel greeting = new JLabel("Good day");
// aFrame.add(greeting);
Container contentPane = aFrame.getContentPane();
contentPane.add(greeting);
}
}

25
Chapter-1
AWT and Swing

You can change the text in a JLabel by using the Component class setText() method
with the JLabel object and passing a String to it.

For example, the following code changes the value displayed in the greeting JLabel:
greeting.setText(“Sample label");

You can retrieve the text in a JLabel (or other Component) by using the getText()
method,
which returns the currently stored String.

To give a JLabel object a new font, you can create a Font object, as in the following:

Font headlineFont = new Font("Monospaced", Font.BOLD, 36);

The typeface name is a String, so you must enclose it in double quotation marks.

26
Chapter-1
AWT and Swing

Example
import java.awt.*;
import javax.swing.*;
public class JFrame5
{
public static void main(String[] args)
{
final int FRAME_WIDTH = 250;
final int FRAME_HEIGHT = 100;
Font headlineFont = new Font("Arial", Font.BOLD, 36);
JFrame aFrame = new JFrame("Fifth frame");
aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
aFrame.setVisible(true);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel greeting = new JLabel("Good day");
greeting.setFont(headlineFont);
// aFrame.add(greeting);
Container contentPane = aFrame.getContentPane();
contentPane.add(greeting);
} 27
Chapter-1
AWT and Swing

More example, adding button component to Frame


import java.awt.*;
public class JFrame2
{
public static void main(String [] args)
{
Frame f = new Frame("A simple window");

Button cancel = new Button("Cancel");


f.add(cancel); //Add the Button to the Frame
f.setSize(100,100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

28
Chapter-1
AWT and Swing

The following table shows the class names for Swing components (including those used
as containers).

29
Chapter-1
AWT and Swing

Layout Managers
When you want to add multiple components to a JFrame or other container, you
usually need to provide instructions for the layout of the components.
For example, the following shows an application in which two JLabels are created and
added to a JFrame in the final statements.
import javax.swing.*;
import java.awt.*;
public class JFrame2
{
Although two JLabels are added to
the frame, only the last one added is
public static void main(String [] args)
visible.
{
final int FRAME_WIDTH = 250;
The second JLabel has been placed
final int FRAME_HEIGHT = 100; on top of the first one, totally
JFrame aFrame = new JFrame("Fifth frame"); obscuring it.
aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
aFrame.setVisible(true); If you continued to add more
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabels to the program, only the last
JLabel greeting = new JLabel("Hello"); one added to the JFrame would be
JLabel greeting2 = new JLabel("Who are visible.you?");

aFrame.add(greeting);
aFrame.add(greeting2);
} 30
Layout Managers Chapter-1
AWT and Swing

Inheritance hierarchy for the Component class

31
Chapter-1
AWT and Swing

Layout Managers
To place multiple components at specified positions in a container so they do not hide
each other, you must explicitly use a layout manager—a class that controls component
positioning.

A container can be assigned one layout manager, which is done using the
setLayout() method of the java.awt.Container class:

public void setLayout(LayoutManager m)

LayoutManager is an interface that all the layout managers’ classes must


implement.

you can use one of the many layout managers of the AWT and Swing APIs,
including the following:

java.awt.FlowLayout.
Lays out components in a left-to-right flow, with each component given its
32
preferred size. A Panel has FlowLayout by default.
Chapter-1
AWT and Swing

Layout Managers

java.awt.BorderLayout.
Divides a container into five regions, allowing one component to be added to
each region. A Frame and the content pane of a JFrame have BorderLayout by
default.

java.awt.GridLayout.
Divides a container into a grid of rows and columns, with one component
added to each region of the grid and each component having the same size.

java.awt.GridBagLayout.
Divides a container into regions similar to GridLayout, except that components
do not need to be the same size. Components can span more than one row or
column.

java.awt.CardLayout.
Each component added to the container is treated as a card, with only one card
being visible at a time (similar to a deck of cards).

javax.swing.BoxLayout.
Allows components to be laid out vertically or horizontally. BoxLayout is similar
to GridBagLayout, but it is generally easier to use. 33
Chapter-1
AWT and Swing

Layout Managers

javax.swing.SpringLayout.
Lays out components with a specified distance between the edges of each
component.

javax.swing.OverlayLayout.
Displays components over the top of each other, similarly to CardLayout. This is
a useful layout manager for creating tabbed panes.

Any container can use any layout manager.

FlowLayout Manager
FlowLayout has the following properties:

• Components are given their preferred size.

• The order in which the components are added determines their order in the
container. The first component added appears to the left, and subsequent
components flow in from the right. 34
Chapter-1
AWT and Swing

• If the container is not wide enough to display all of the components, the components
wrap around to a new line.
• You can control whether the components are centered, left-justified, or right-justified.
• You can control the vertical and horizontal gap between components

Note;
A FlowLayout manager will not attempt to override the width or height of a component if
you have previously declared a specific size for the component.

To use FlowLayout in a Frame or JFrame, you need to invoke setLayout() on


the container and pass in a new FlowLayout object.

The FlowLayout class has three constructors:

public FlowLayout().
Creates a new FlowLayout that centers the components with a horizontal
and vertical gap of five units (where the unit is pixels in most GUI operating
systems). 35
Chapter-1
AWT and Swing

public FlowLayout(int align).


Creates a FlowLayout object with the specified alignment, which is one of
the following values:

FlowLayout.CENTER, FlowLayout.RIGHT, or FlowLayout.LEFT.


The horizontal and vertical gap between components is five units.

public FlowLayout(int align, int hgap, int vgap).


Creates a FlowLayout object with the specified alignment, horizontal gap,
and vertical gap.

For example, the following statement instantiates a new FlowLayout


manager that justifies components to the right.
Frame f = new Frame();
f.setLayout(new FlowLayout(FlowLayout.RIGHT));

The horizontal and vertical gap is not specified, so they will have the default
value of 5.
36
Chapter-1
AWT and Swing

Example
import javax.swing.*;
import java.awt.*;
public class JFrame6
{
public static void main(String[] args)
{
final int FRAME_WIDTH = 250;
final int FRAME_HEIGHT = 100;
JFrame aFrame = new JFrame("Sixth frame");
aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
aFrame.setVisible(true);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel greeting = new JLabel("Hello");
JLabel greeting2 = new JLabel("Who are you?");
aFrame.setLayout(new FlowLayout());
aFrame.add(greeting);
aFrame.add(greeting2);
} 37
Chapter-1
AWT and Swing

Example 2
import java.awt.*;
import javax.swing.JFrame;
public class FlowLayoutDem
{
public static void main(String [] args)
{
JFrame f = new JFrame("FlowLayout demo");
f.setLayout(new FlowLayout());
Container con=f.getContentPane();
con.add(new Button("Red"));
con.add(new Button("Blue"));
con.add(new Button("White"));
List list = new List();
list.add("Addis Ababa");
list.add("Hawassa");
list.add("Wolaita");

con.add(list);
con.add(new Checkbox("Pick me", true));
con.add(new Label("Enter name here:"));
con.add(new TextField(20));
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
38
}
Chapter-1
AWT and Swing

The placement orientation is set to left-to-right using the following statement:


con.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

Because the default orientation is left-to-right, this statement is not


necessary. However, you can experiment with a different orientation by
changing the constant to RIGHT_TO_LEFT

con.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

That would look like as below

39
Chapter-1
AWT and Swing

BorderLayout Manager
The java.awt.BorderLayout class represents a BorderLayout manager, which divides a
container into five different regions: north, south, east, west, and center.

Only one component can be added to a given region, and the size of the component is
determined by the region it appears in.

BorderLayout has the following properties:


• When a component is added, you pass in an int to the add() method that
denotes the region of the container in which the component is to be
added.
The possible values are NORTH, SOUTH, EAST, WEST, and CENTER, which are
all static fields in the BorderLayout class.

• You do not need to add a component to each region. If a region is left


empty, the area is filled with the other components in the neighboring
regions.

40
• A component added to the north or south gets its preferred height, but its
Chapter-1
AWT and Swing

• A component added to the east or west will get its preferred width, but its height will
be the height of the container minus any components in the north or south.

• A component added to the center gets neither its preferred height nor width, but
instead will be the size of the remaining space not filled by components in the other
four regions.

If you want a Frame or JFrame to use BorderLayout, you do not need to


invoke setLayout() because they use BorderLayout by default.

If your container does not have BorderLayout, you need to instantiate a


new BorderLayout object using one of its two constructors:

public BorderLayout().
Creates a new BorderLayout with a horizontal and vertical gap of five units
between components.
public BorderLayout(int hgap, int vgap).
Creates a BorderLayout object with the specified horizontal and vertical gap.
41
Chapter-1
AWT and Swing

Example
import javax.swing.*;
import java.awt.*;
public class JDemoBorderLayout extends JFrame
{
private JButton nb = new JButton("North Button");
private JButton sb = new JButton("South Button");
private JButton eb = new JButton("East Button");
private JButton wb = new JButton("West Button");
private JButton cb = new JButton("Center Button");
private Container con = getContentPane();
public JDemoBorderLayout()
{
con.setLayout(new BorderLayout());
con.add(nb, BorderLayout.NORTH);
con.add(sb, BorderLayout.SOUTH);
con.add(eb, BorderLayout.EAST);
con.add(wb, BorderLayout.WEST);
con.add(cb, BorderLayout.CENTER);
setSize(400, 150);
}
public static void main(String[] args)
{
JDemoBorderLayout frame = new JDemoBorderLayout();
frame.setVisible(true);
frame.setTitle("BordeLayout Demo");
42
}
Chapter-1
AWT and Swing

BorderLayout are used to nest a panel inside one of the regions

A panel is a simple container used for holding components.

A panel is like an invisible container, and it must be placed in a top-level


container, such as a Frame or JFrame before it can be viewed.

The java.awt.Panel class represents panels in AWT, and the


javax.swing.JPanel class represents panels in Swing.

Panels have the following properties:

• The default layout manager of both Panel and JPanel is FlowLayout, but
since they are containers, they can have any layout manager assigned to
them.

• A panel can be nested within another panel, a common occurrence when


working with complex GUIs.

The Panel class has two constructors:


public Panel().
43
Creates a new Panel with FlowLayout
Chapter-1
AWT and Swing

public Panel(LayoutManager m).


Creates a new Panel with the specified layout manager.

The JPanel class has four constructors:

public JPanel().
Creates a new JPanel with FlowLayout and doublebuffering turned on.

public JPanel(boolean isDoubleBuffered).


Creates a new JPanel with FlowLayout. It will use a double buffer if the boolean
parameter is true.

public JPanel(LayoutManager m).


Creates a new JPanel with the specified layout manager and double-buffering turned
on.

public JPanel(LayoutManager m, boolean isDoubleBuffered).


Creates a new JPanel with the specified layout manager, with double-buffering used
when the boolean parameter is true.

44
import java.awt.*;
public class PanelDemo extends Frame
{
private Button next, prev, first;
private List list;
public PanelDemo(String title)
{
super(title);
next = new Button("Next >>");
prev = new Button("<< Previous");
first = new Button("First");
Panel southPanel = new Panel();
southPanel.add(prev);
southPanel.add(first);
southPanel.add(next);
this.add(southPanel, BorderLayout.SOUTH);
Panel northPanel = new Panel();
northPanel.add(new Label("Make a selection"));
this.add(northPanel, BorderLayout.NORTH);
list = new List();
for(int i = 1; i <= 10; i++)
{
list.add("Selection " + i);
}
this.add(list, BorderLayout.CENTER);
}
public static void main(String [] args)
{
Container f = new PanelDemo("PanelDemo");
f.setSize(300,200);
f.setVisible(true);
45
GridLayout Manager
The java.awt.GridLayout class represents a layout manager that divides a
container into a grid of rows and columns.

The order in which components are added determines their locations in the
grid.

The first component added appears in the first row and column, and
subsequent components fill in the columns across the first row until that row
is filled. Then, the second row is filled, and then the third, and so on.

To instantiate a GridLayout object, you use one of its three constructors:

public GridLayout(int rows, int cols).


Creates a new GridLayout with the specified number of rows and columns.
The horizontal and vertical gap between components is five units.

public GridLayout(int rows, int cols, int hgap, int vgap).


Creates a new GridLayout with the specified number of rows and columns
and also with the specified horizontal and vertical gap.

public GridLayout().
Creates a GridLayout object with one row and any number of columns. 46
The no-argument constructor of GridLayout creates a GridLayout with one
row and an indeterminate number of columns.

This is equivalent to the following statement:


new GridLayout(1,0);

For example, suppose that we instantiate a GridLayout manager with three


columns and 0 rows:

GridLayout grid = new GridLayout(0, 3);

If 10 components are added to a container with grid as its layout manager,


the components will be displayed in four rows and three columns, with the
last row containing only one component.

Example

47
import java.awt.*;
import javax.swing.*;
public class GridLayoutDemo extends JFrame
{
private JButton [ ] buttons;
public GridLayoutDemo(String title)
{
super(title);
Container contentPane = this.getContentPane();
contentPane.setLayout(new GridLayout(2,3,10,15));
buttons = new JButton[6];
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton("Click " + (i + 1));
contentPane.add(buttons[i]);
}
}
public static void main(String [] args)
{
JFrame f = new GridLayoutDemo("GridLayoutDemo");
f.setSize(300,200);
f.setVisible(true);
}
} 48
BoxLayout Manager
The javax.swing.BoxLayout class represents a box layout

If the components are aligned horizontally, the BoxLayout manager attempts


to give them all the same height, based on the component with the largest
height. Components in this axis get their preferred width.

If the components are aligned vertically, the BoxLayout manager attempts


to give them all the same width, based on the component with the largest
width. Components in this axis get their preferred height.

In most situations, the Box class is used when working with BoxLayout, as
opposed to creating a BoxLayout manager directly.

The BoxLayout class has one constructor:

public BoxLayout(Container target, int axis).


Creates a new BoxLayout manager for the specified target and given axis.

The possible values of axis are as follows:

BoxLayout.X_AXIS.
The components are displayed horizontally from left to right.
49
BoxLayout.Y_AXIS.
The components are displayed vertically from top to bottom.

BoxLayout.LINE_AXIS.
Similar to X_AXIS, the components are laid out horizontally.

The order they are displayed is different, depending on the container’s


ComponentOrientation property, which allows components to be displayed
from right to left or from left to right.

BoxLayout.PAGE_AXIS.
Components are laid out like words on a page based on the container’s
ComponentOrientation property, which allows the components to be laid out
from right to left, from left to right, from top to bottom, or from bottom to
top.

The simplest way to use BoxLayout is to instantiate a Box object, place your
components in the Box, and place the Box into your container.

The constructor of the Box class takes in one of these axis values as well:

public Box(int axis)

50
import java.awt.*;
import javax.swing.*;
public class BoxLayoutDemo extends JFrame
{
public BoxLayoutDemo(String title)
{
super(title);
//Create a Box with a vertical axis.
Box box = new Box(BoxLayout.Y_AXIS);
//Add some components to the Box.
box.add(new JButton("OK"));
box.add(new JCheckBox("Check here."));
box.add(new JButton("Click here to continue."));
box.add(new JLabel("Enter your name:"));
box.add(new JTextField());
//Add the Box to the content pane of this JFrame.
Container contentPane = this.getContentPane();
contentPane.add(box, BorderLayout.CENTER);
}
public static void main(String [] args)
{
JFrame f = new BoxLayoutDemo("BoxLayoutDemo");
f.pack();
f.setVisible(true);
} 51
You can create a GUI with components in the exact location and size that you want.
To do this, you set the layout manager of the container to null and then set the bounds
for each component within the container using the setBounds() method
Example
import java.awt.*;
import javax.swing.*;
public class JDialogDemo extends JFrame
{
private JButton ok, cancel;
public JDialogDemo(String title)
{
this.setTitle(title);
Container contentPane = this.getContentPane();
contentPane.setLayout(null);
JLabel message = new JLabel("Continue?");
message.setBounds(70, 20, 125, 20);
ok = new JButton("OK");
ok.setBounds(15,50, 60, 20);
cancel = new JButton("Cancel");
cancel.setBounds(90, 50, 80, 20);
contentPane.add(message);
contentPane.add(ok);
contentPane.add(cancel);
}
public static void main(String [] args)
{
Jframe f = new JDialogDemo("JDialogDemo");
f.setSize(200,100);
f.setSize(250, 130);
f.setVisible(true);
} 52
}
The GridBagLayout
Like the GridLayout manager, this layout manager places the components
in grid cells.

Unlike the GridLayout manager, the row heights and the column widths
may not remain equal when the components are placed using this layout
manager.

The GridBagLayout manager honors the components’ preferred sizes while


determining the row heights and column widths.

A component may span multiple rows and columns. While adding a


component, you set the constraints on its placement, as is done with the
following code snippet:

JPanel pane = new JPanel(new GridBagLayout());


GridBagConstraints gridBagConstraints = new GridBagConstraints();
// set fields on gridBagConstraints
pane.add(theComponent, gridBagConstraints);

You create an instance of the GridBagConstraints class, set its desired fields, and
53
pass it as a parameter to the add method
Example
We set a few properties for this constraints object. Suppose these
properties are common to all the components we are going to place
on the container:
constraints.ipady = 15;
constraints.ipadx = 10;
constraints.fill = GridBagConstraints.BOTH;

The ipady and ipadx properties define the internal padding of the
component, which is how much space to add to the minimum height or width
of the component.

Setting the fill property to the predefined BOTH constant indicates that the
component should occupy all the available space in the given grid cell.

The other possible values are;

• the HORIZONTAL value makes the component stretch horizontally to fill the
available width,

• the VERTICAL value makes the component stretch vertically, and


54
Suppose that we have a label object referenced to by jLabeloutput
To set a few properties of the label, we can do;
jLabelOutput.setFont(new Font("Monospaced", 1, 24));
jLabelOutput.setBorder(new MetalBorders.TextFieldBorder());

These two statements set the font for the text in the label and set a border
around the label boundary.

We will now set a few additional constraints specific to this label:


constraints.insets = new Insets(10, 10, 10, 10);

Here, insets defines the external padding of the component, which is the
minimum amount of space between the component and the edges of its
display area.
The next property we set is the gridWidth:
constraints.gridwidth = GridBagConstraints.REMAINDER;

The gridWidth property specifies the number of cells in a row for the
component’s display area. 55
The possible values that can be assigned to the gridWidth property are;

• REMAINDER, which specifies that this is the last component in the current
row.

• RELATIVE, which adds the next component to the same row immediately
following the previously added component.

We now add the label to the container by calling the add method of the
container:

getContentPane().add(jLabelOutput, gridBagConstraints);

Note that the second parameter specifies the constraints object we have set
up so far

You can then reset the constraint for the next component to be added or use
the same constraint.

Example, the inset component can be reset as;


gridBagConstraints.insets = new Insets(0, 0, 0, 0);
56
Note that, so far, the layout manager does not know the number of columns,
To add a component, we first set its grid location by setting the gridx and
gridy properties:
For example;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
This indicates that the component to be added should be placed in Column
0, Row 1

The trick comes in placing a component, which occupies two [or more ]
columns’ worth of space. We do this by using the following code fragment:
gridBagConstraints.gridwidth = 2;

Likewise, to place a component, which is two rows high, we set the


gridHeight property of the constraints object:
gridBagConstraints.gridheight = 2;
Example
import javax.swing.*;
import javax.swing.plaf.metal.MetalBorders;
import java.awt.*;
57
public class Calc extends JFrame {
private JLabel jLabelOutput = new JLabel(“1010111010", SwingConstants.RIGHT);
private JButton jButton0 = new javax.swing.JButton("0");
private JButton jButton1 = new javax.swing.JButton("1");
private JButton jButtonEqual = new javax.swing.JButton("=");
private JButton jButtonAdd = new javax.swing.JButton("+");
public Calc() {
super.setTitle("Calculator");
initGUI();
}
private void initGUI()
{ setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
GridBagConstraints constraints = new GridBagConstraints();
constraints.ipady = 15;
constraints.ipadx = 10;
constraints.fill = java.awt.GridBagConstraints.BOTH;
getContentPane().setLayout(new GridBagLayout());
jLabelOutput.setFont(new Font("Monospaced", 1, 24));
jLabelOutput.setBorder(new MetalBorders.TextFieldBorder());
58
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridwidth = GridBagConstraints.REMAINDER;
getContentPane().add(jLabelOutput, constraints);
constraints.insets = new Insets(0, 0, 0, 0);
constraints.gridwidth = 1;
constraints.gridx = 0;
constraints.gridy = 1;
getContentPane().add(jButton0, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
getContentPane().add(jButton1, constraints);
constraints.gridwidth = 2;
constraints.gridx = 0;
constraints.gridy = 2;
getContentPane().add(jButtonEqual, constraints);
constraints.gridheight = 2;
constraints.gridx = 2;
constraints.gridy = 1;
getContentPane().add(jButtonAdd, constraints);
pack();
}
public static void main(String args[]) {
new Calc().setVisible(true);
} 59
}
Event handling
The Delegation Model
Events in Java are fired and handled using a design known as the delegation
model.

The delegation event model is based on the concept that for every event, there is an
event source and an event listener. Just as illustrated below

An event source either generates an event on its own or is subject to the occurrence of
an external event.

Any object may act as an event source, an event listener, or both.

There are three major players in the delegation model:


60
The o event source .
• An event source is a component that generates an event.

• Events are Java objects that are instantiated by the component and passed as an
argument to any listeners.

• The JButton, JCheckbox, JTextArea, and JTextField classes in the Swing


package are a few examples of event sources.

• All classes that derive from java.awt.Component are candidate event sources

The Event Listener


• For every event source there may be one or more registered listeners.

• The objects that are interested in the occurrence of a particular event will register
themselves with the corresponding event source.

• This means that an interested event listener sends its own object reference to the
event source.

• The event source copies this reference into its own storage and calls a specified
callback method on the event listener whenever it generates an event.

61
Thus, the event source is responsible for maintaining the list of registered event
listeners and is also responsible for transmitting the appropriate event to these listeners
whenever such an event is generated.

62
A listener may be interested in more than one event occurring from more than one
event source.

In such a case, the event listener registers itself with all the desired event sources, as
illustrated below

Whenever an event source generates an event, it transmits the event to the registered
listener by calling a method of the listener object.

An interface.
• The interface contains the methods that the listener must implement and that the
source of the event invokes when the event occurs. 63
Multiple Event Types
Java classifies events into multiple types.

For example, an event may be classified as a mouse event, a keyboard event, a


window event, and so on.

As shown in the figure above, whenever the mouse enters the component body, a
mouseEntered event is generated.

When the mouse exits the component body, a mouseExited event occurs.

When you click the mouse on a component, a mouseClicked event occurs. 64


Alphabetical list of some event listeners

A unique event handler is provided to handle each type of event.

Events can be divided into two groups:


low-level events and semantic events.

Low-level events represent window-system occurrences or low-level input.


Everything else is a semantic event. 65
Here are the most commonly used semantic event classes in the java.awt.event
package:

• ActionEvent (for a button click, a menu selection, selecting a list item, or Enter
typed in a text field)

• AdjustmentEvent (the user adjusted a scrollbar)

• ItemEvent (the user made a selection from a set of checkbox or list items)

Five low-level event classes are commonly used:

• KeyEvent (a key was pressed or released)

• MouseEvent (the mouse button was pressed, released, moved, or dragged)

• MouseWheelEvent (the mouse wheel was rotated)

• FocusEvent (a component got focus or lost focus)

• WindowEvent (the window state changed)

66
Some Swing components and their associated listener-registering methods

67
Java uses a standard naming convention for event classes and listener interfaces:

The name of the event class uses the convention <Name>Event,

and the corresponding listener interface uses the convention <Name>Listener.

For example, the ActionEvent class is associated with the one method of the
ActionListener interface,

and the WindowEvent class is associated with the seven methods of the
WindowListener interface.

You can tell what kinds of events a component can fire by looking at the kinds of event
listeners you can register on it.

For example, the JComboBox class defines these listener registration methods:

addActionListener
addItemListener
addPopupMenuListener
68
Thus, a combo box supports action, item, and popupmenu listeners in addition to the
listener methods it inherits from JComponent

Because all Swing components descend from the AWT Component class, you can
register the following listeners on any Swing component:

component listener
Listens for changes in the component's size, position, or visibility.

focus listener
Listens for whether the component gained or lost the keyboard focus.

key listener
Listens for key presses; key events are fired only by the component that has the
current keyboard focus.

mouse listener
Listens for mouse clicks, mouse presses, mouse releases and mouse movement into
or out of the component's drawing area.

69
mouse-motion listener
Listens for changes in the mouse cursor's position over the component.

mouse-wheel listener
Listens for mouse wheel movement over the component.

Hierarchy Listener
Listens for changes to a component's containment hierarchy of changed events.

Hierarchy Bounds Listener


Listens for changes to a component's containment hierarchy of moved and resized
events.

Example
The following program demonstrates how to create a push button and respond to
button- press events.

// Demonstrate a push button and handle action events.


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

70
class ButtonDemo implements ActionListener {
JLabel jlab;
ButtonDemo() {

// Create a new JFrame container.


JFrame jfrm = new JFrame("A Button Example");

// Specify FlowLayout for the layout manager.


jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.


jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make two buttons.


JButton jbtnUp = new JButton("Up"); Create two push
JButton jbtnDown = new JButton("Down"); buttons.

// Add action listeners.


jbtnUp.addActionListener(this);
Add action listeners
jbtnDown.addActionListener(this);
for the buttons.
71
// Add the buttons to the content pane.
jfrm.add(jbtnUp); Add the buttons to
jfrm.add(jbtnDown); the content pane.

// Create a label.
jlab = new JLabel("Press a button.");

// Add the label to the frame.


jfrm.add(jlab);

Handle button
// Display the frame. events.
jfrm.setVisible(true);
}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Up"))
jlab.setText("You pressed Up.");
else
jlab.setText("You pressed down. ");
} Use the action command to
determine which button was
pressed.
72
public static void main(String args[]) {
// Create the frame
ButtonDemo btn = new ButtonDemo();

}
} Initial state When button Up is clicked When button Down is clicked

Example 2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TFDemo implements ActionListener
{
JTextField jtf;
JButton jbtnRev;
JLabel jlabPrompt, jlabContents;
73
TFDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Use a Text Field");

// Specify FlowLayout for the layout manager.


jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.


jfrm.setSize(240, 120);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a text field.


Create a text field that is 10
jtf = new JTextField(10);
columns wide.
// Set the action commands for the text field.
jtf.setActionCommand("myTF");

// Create the Reverse button.


JButton jbtnRev = new JButton("Reverse");

// Add action listeners.


jtf.addActionListener(this); Add the textfield and the
74
jbtnRev.addActionListener(this); button
// Create the labels.
jlabPrompt = new JLabel("Enter text: ");
jlabContents = new JLabel("");

// Add the components to the content pane.


jfrm.add(jlabPrompt);
jfrm.add(jtf);
jfrm.add(jbtnRev);
jfrm.add(jlabContents);
This method handles both
// Display the frame. button and textfield events.
jfrm.setVisible(true);
}
// Handle action events.
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Reverse")) {
// The Reverse button was pressed.
String orgStr = jtf.getText();
String resStr = ""; Use the action command to
// Reverse the string in the text field. determine which
for(int i=orgStr.length()-1; i >=0; i--) component generated the
resStr += orgStr.charAt(i); event.
// Store the reversed string in the text field.
jtf.setText(resStr); 75
} else
// Enter was pressed while focus was in the
// text field.
jlabContents.setText("You pressed ENTER. Text is: " +
jtf.getText());
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
TFDemo tf= new TFDemo();
}
}
Initial state When reverse button is clicked When enter key is pressed

76
Example 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CBDemo implements ItemListener {
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Demonstrate Check Boxes");

// Specify FlowLayout for the layout manager.


jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.


jfrm.setSize(280, 120);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

77
// Create empty labels.
jlabSelected = new JLabel("");
jlabChanged = new JLabel("");

// Make check boxes.


jcbAlpha = new JCheckBox("Alpha");
jcbBeta = new JCheckBox("Beta"); Create the
jcbGamma = new JCheckBox("Gamma"); checkboxes.

//add Item Listners


jcbAlpha.addItemListener(this);
Add to Item listners
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);

// Add check boxes and labels to the content pane.


jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
78
// This is the handler for the check boxes.
public void itemStateChanged(ItemEvent ie) { Handle check box item
String str = ""; events.
// Obtain a reference to the check box that caused the event.
JCheckBox cb = (JCheckBox) ie.getItem(); Get a reference to the
check box that changed.
// Report what check box changed.
if(cb.isSelected()) Determine what happened.
jlabChanged.setText(cb.getText() + " was just selected.");
else
jlabChanged.setText(cb.getText() + " was just cleared.");
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
jlabSelected.setText("Selected check boxes: " + str);
}
79
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
CBDemo cbs= new CBDemo();
}
}
Initial state Alpha selected Alpha, & Betaselected

Alpha, Beta & Gamma selected Alpha & Gamma selected, Beta
cleared

80
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
CBDemo cbs= new CBDemo();
}
}

Event Handling Summary

81
Event Handling Summary

82
Event Handling Summary

83

You might also like