CH 1
CH 1
School of Informatics
Department of Computer Science
Advanced Programming
1
Chapter-1
AWT and Swing
• To build GUIs and handle events generated by user interactions with GUIs.
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.
GUIs are built from GUI components. These are sometimes called controls or widgets.
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;
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.
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.
The classes and interfaces of Swing are found in the javax.swing packages.
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
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:
. 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
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 pack(). Sets the size of the Frame to be just big enough to
display all its components with their preferred size
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:
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.
11
Chapter-1
AWT and Swing
Example 2
import javax.swing.*;
public class JavaApplication1
{
public static void main(String [] args)
{
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
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)
{
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
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.
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:
Inheritance hierarchy for the frame and component classes in AWT and Swing
Back
18
Chapter-1
AWT and Swing
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
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.
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
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
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
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.
For example, the following statements add a JButton to the content pane of a
JFrame:
22
Chapter-1
AWT and Swing
The inheritance hierarchy of the JLabel class is shown in the figure below
JLabel() creates a JLabel instance with no image and with an empty string for
the title.
23
Chapter-1
AWT and Swing
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:
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
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
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:
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.
FlowLayout Manager
FlowLayout has the following properties:
• 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.
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
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
con.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
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.
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.
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
• 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.
public JPanel().
Creates a new JPanel with FlowLayout and doublebuffering turned on.
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.
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.
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
In most situations, the Box class is used when working with BoxLayout, as
opposed to creating a BoxLayout manager directly.
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.
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:
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.
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 HORIZONTAL value makes the component stretch horizontally to fill the
available width,
These two statements set the font for the text in the label and set a border
around the label boundary.
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.
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;
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.
• Events are Java objects that are instantiated by the component and passed as an
argument to any listeners.
• All classes that derive from java.awt.Component are candidate event sources
• 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.
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.
• ActionEvent (for a button click, a menu selection, selecting a list item, or Enter
typed in a text field)
• ItemEvent (the user made a selection from a set of checkbox or list items)
66
Some Swing components and their associated listener-registering methods
67
Java uses a standard naming convention for event classes and listener interfaces:
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.
Example
The following program demonstrates how to create a push button and respond to
button- press events.
70
class ButtonDemo implements ActionListener {
JLabel jlab;
ButtonDemo() {
// Create a label.
jlab = new JLabel("Press a button.");
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");
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");
77
// Create empty labels.
jlabSelected = new JLabel("");
jlabChanged = new JLabel("");
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();
}
}
81
Event Handling Summary
82
Event Handling Summary
83