You are on page 1of 69

TCS Confidential

1
AWT & Swing
Java Programming
TCS Confidential
2
The AWT & Swing
(Graphics, Color, Font, Controls)
AWT - Abstract Windowing Toolkit
AWT Class Hierarchy
Frame Windows
Creating Frame Windows in
Applets
Working with Graphics, Colors,
and Fonts
TCS Confidential
3
AWT Controls: Label, Button,
Checkbox, CheckboxGroup,
Choice, List, TextField,
TextArea.
Swing - Swing Controls
Customizing Controls
Look-and-Feel
The AWT & Swing
(Graphics, Color, Font, Controls)
TCS Confidential
4
AWT
Abstract Windowing Toolkit
Contains numerous classes and
methods that allow to create and
manage windows
Main purpose is to support
applet windows
Can also be used to create
stand-alone windows that run in
a GUI environment, such as
Windows
TCS Confidential
5
The AWT Class Hierarchy
OBJECT
OBJECT
COMPONENT
CONTAINER
WINDOW PANEL
FRAME
BUTTON CANVAS
DIALOG
LABEL
COLOR FONT GRAPHICS
AWT classes are
contained in
java.awt package.
APPLET
TCS Confidential
6
The Frame Windows
Frame - a window that has a
title bar, menu bar, border,
cursor, and an icon image
Window - not created
directly but through the
Frame subclass as child
windows within applets, and
child/ top-level windows for
applications
TCS Confidential
7
The Frame Windows
Event handlers of a Frame
window can handle their own
events just the same way as
those of applets main
window do
Title in the frame window can
be changed by setTitle()
TCS Confidential
8
The Frame Windows
setSize() , getSize() - used to set
and obtain dimensions of window
specified by its width and height
fields
The window frame after creation will
not be visible until the
setVisible(true) is called
The window should be closed at the
end of program by calling
setVisible(false)
TCS Confidential
9
Creating Frame Window in Applet
Create a subclass of Frame
Override any of standard
window methods: init(),
start(), stop(), paint()
Finally, implement
windowClosing() method of
WindowListener interface
TCS Confidential
10
Creating Frame Window in Applet
Create an object of the Frame
subclass
This causes an invisible frame
window of default height and
width to come in existence
Call setVisible(true) to make it
visible, and set its size by
setSize()
TCS Confidential
11
Demo - AppletFrame.java
The applet creates a subclass of
Frame called SampleFrame
A window object of
SampleFrame is instantiated
within init() of applet
The start() and stop() methods
of applet are overridden here to
show and hide the child window
automatically
TCS Confidential
12
Demo - AppletFrame.java
TCS Confidential
13
Working with Graphics
All graphics are drawn
relative to a window
This can be the main window
of an applet, a child window
of an applet, or a stand-alone
application window
TCS Confidential
14
Working with Graphics ...
Drawing lines:
void drawLine( int StartX, int
StartY, int endX, endY )
Demo (RulerApplet.java) :
Uses drawLine method to draw a
ruler like lines
TCS Confidential
15
Working with Graphics ...
Drawing outlined and filled
rectangles:
void drawRect
(int top, int left, int width, int height)
void fillRect
(int top, int left, int width, int height)
The upper-left corner of rectangle is
at top, left. The dimensions are
specified by width and height
TCS Confidential
16
Drawing rounded outlined and filled
rectangles:
void drawRoundRect(int top, int left, int
width, int height, int xDiam, int yDiam)
void fillRoundRect(int top, int left, int
width, int height, int xDiam, int yDiam)
The diameter of the rounded arc
along X and Y axes is specified by
xDiam and yDiam
Working with Graphics ...
TCS Confidential
17
Working with Graphics ...
Drawing outlined and filled ellipses
and circles:
void drawOval(int top, int left, int width,
int height)
void fillOval(int top, int left, int width, int
height)
Ellipse is drawn within a bounding
rectangle whose upper left corner is
specified by top, left
TCS Confidential
18
Working with Graphics ...
Drawing outlined and filled arcs:
void drawArc( int top, int left, int width, int
height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int
height, int startAngle, int sweepAngle)
Arc is bounded by rectangle whose
upper-left corner is specified by top,
left
TCS Confidential
19
Working with Graphics ...
The arc is drawn from startAngle
through the angular distance in
degrees specified by sweepAngle
Arc is drawn counterclockwise if
sweepAngle is positive else
clockwise. Zero degree is on
horizontal, at 3 oclock position
The start and sweep angles would
be 90
0
and 180
0
to draw an arc from
12 to 6 oclock
TCS Confidential
20
Working with Graphics ...
Drawing Polygons (arbitrarily shaped
figures)
void drawPolygon(int x[ ], int y[ ], int
numPoints)
void fillPolygon(int x[ ], int y[ ], int
numPoints)
Polygons endpoints are specified
within x & y arrays. numPoints
specifies the number of points
TCS Confidential
21
Color is encapsulated by the
java.awt.Color class supported
by Java in a portable, device-
independent fashion
Commonly used constructors:
Color(int red, int green, int blue)
red, green, and blue must be
between 0 - 255
Working with Color
TCS Confidential
22
Working with Color
Color(int rgbValue)
int rgbValue is organized with red in
bits 16 to 23, green in bits 8 to 15,
and blue in bits 0 to 7
Color(float red, float green, float
blue)
red, green, and blue must be
between 0.0 - 1.0
Methods that help manipulate colors:
brighter(), darker() etc.
TCS Confidential
23
Graphics Methods & Colors
Color for your graphics
Set color on Graphics object
Graphics method uses
current color of the Graphics
object
Use setColor(Color clr)
method of Graphics object
TCS Confidential
24
(ColoredGraphics.java)
Uses the different draw & fill methods
for drawing line, rectangle, rounded
rectangle, oval, arc, polygon, etc.
Demo
TCS Confidential
25
Sizing Graphics
Size a graphics object to fit the
current size of the window in which
it is drawn
Obtain current dimensions by
calling getSize() on window object
It is returned encapsulated within a
java.awt.Dimension object
Scaled graphical objects
accordingly
(SizableGraphics.java)
TCS Confidential
26
Working with Fonts
The AWT supports multiple type
fonts that are encapsulated by the
Font class
Fonts have a family name (Courier,
TimesNewRoman, etc), a logical
font name such as Monospaced
specifying the category of font, and
a face name such as Bold, Italic etc.
TCS Confidential
27
Working with Fonts
Creating and Selecting a font: First
construct a Font object that describes
that font as follows:
Font(String fontName, int fontStyle, int
fontSize)
The fontStyle may consist of one or
more of these constants: Font.PLAIN,
Font.BOLD, Font.ITALIC.
To combine, OR them together as:
Font.BOLD + Font.ITALIC
TCS Confidential
28
AWT supports the following types
of controls:
Labels
Push Buttons
Check Boxes
Choice Lists
Lists
Text Fields
Using AWT Controls
TCS Confidential
29
Using AWT Controls
Adding a control in a window
Create an instance of the
control
Add it to the window by
calling add() defined by
Container class
A control can be removed from a
window by remove()
TCS Confidential
30
A label is a passive control
Does not support any
interaction with the user
Displays a string
Demo: LabelDemo.java
Using Labels
TCS Confidential
31
Using Buttons
Most widely used control
Contains a label
Generates an action event when it is
pressed
The event notification is passed to
any listeners that implement the
ActionListener interface which
defines the actionPerformed() method
TCS Confidential
32
Using Buttons
Constructors:
Button()
Button(String str)
Label of a button can be set and
retrieved by:
setLabel() & getLabel() methods
(Demo of ButtonDemo.java)
TCS Confidential
33
A Checkbox is a control that is
used to turn an option on or off
It has a label and consists of a
small box that can either contain a
check mark or null
Its state can be changed by
checking on it
A checkbox can be used
individually or as a group
Checkbox and CheckboxGroup
TCS Confidential
34
Checkbox and CheckboxGroup
Radio buttons - A set of mutually
exclusive checkboxes
One and only one checkbox in the
group can be checked at any time
Checkbox(), Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on,
CheckboxGroup cbg)
TCS Confidential
35
Checkbox and CheckboxGroup
getState() to retrieve the current
state of a checkbox
setState() to set the state of a
checkbox
getLabel() to obtain the current
label associated with a
checkbox
setLabel() to set its label
TCS Confidential
36
Demo of CheckboxDemo.java
Each time a checkbox is selected or
deselected, an item event is generated
and sent to the registered listeners
Each listener implements the
ItemListener interface that defines the
itemStateChanged()
An ItemEvent object is passed as
argument to this method. It contains the
information whether it was a selection or
a deselection event
TCS Confidential
37
Using Choice Lists
Choice class is used to create a
pop-up list of items from which
the user may choose
A choice list is a form of menu
When inactive, a Choice
component takes up only
enough space to show currently
selected item
TCS Confidential
38
Using Choice Lists
When clicked - whole list of
choices pops up, and new
selection can be made
Defines the default constructor
only - which creates an empty
choice
Call addItem() or add() to add an
item to the list
TCS Confidential
39
Using Choice Lists
Call getSelectedItem() or
getSelectedIndex() to
determine which item is
currently selected
Call getItemCount() to obtain
the number of items in the
list
(Demo of ChoiceDemo.java)
TCS Confidential
40
Using Lists
Provides a compact, multiple-
choice, scrolling selection list
Choice object - shows only the
single selected item
A List object can be constructed
to show any number of choices
in the visible window
Allow multiple selections
TCS Confidential
41
Using Lists
Constructors
List(), List(int numRows),
List(int numRows, boolean
multipleSelect)
Methods for handling Lists:
add(), getSelectedItem(),
getSelectedIndex(), getSelectedItems(),
getSelectedIndexes(), getItem()
(Demo: ListDemo.java)
TCS Confidential
42
The TextField class implements a
single-line text-entry area, usually
called an edit control
Allows to enter strings, edit them
using arrow keys, cut and paste
keys, and mouse selections
getText() returns string contained
in the text field
setText() sets string into the text
field
Using a TextField
TCS Confidential
43
Using a TextField
Allows to select a portion of
the text in a text field
getSelectedText() returns
currently selected text
Whole text can be selected
by calling select()
(Demo: TextFieldDemo.java)
TCS Confidential
44
The Swing
Swing Applets (class JApplet)
Icons ( class ImageIcon & Icon
Interface)
Labels (class JLabel)
Text Fields (class JTextField)
Buttons (class JButton)
Check Boxes (class JCheckBox)
Radio Buttons (class JRadioButton)
Choice Lists (class JComboBox)
Swing Examples
TCS Confidential
45
The Swing
Swing is part of JFC library and an
extension of AWT
It is also AWTs supercharged
alternative for a user interface style
dubbed as Metal
Besides familiar but more capable
components such as buttons, check
boxes, and labels, several exciting
additions like tabbed panes, scroll
panes, trees, and tables are supplied
by Swing
TCS Confidential
46
The Swing
Unlike AWT components, Swing
components are not implemented by
platform-specific code
Written entirely in Java and termed as
lightweight components
Swing enables a Java program to
create an interface that uses the style
of native OS with different look and
feel
TCS Confidential
47
Swing - Model-View-Controller
Model-View-Controller (MVC) Pattern
Model
Represents the
data for the
application
View
Visual
representati
on of data
Controller
Takes user input on the
view and translates that
to changes in the model
TCS Confidential
48
Designing a GUI with Swing
All elements of Swing are part of
javax.swing package
Applets that use Swing must be
subclasses of JApplet that
extends Applet
JApplet is rich with functionality
that is not found in Applet -
supports various panes such
as content pane, glass pane, root
pane
TCS Confidential
49
Designing a GUI with Swing
Adding a component to an instance of
JApplet is different then Applet
Add it to an intermediate container
called content pane by calling add()
method of Container
The content pane is obtained via the
method getContentPane()
Another pane can be obtained by
JPanel that can be set to content pane
by the method setContentPane()
TCS Confidential
50
Icons
Icons are encapsulated by
ImageIcon class that paints an
icon from an image and
implements the Icon interface
The constructors are:
ImageIcon(String filename)
ImageIcon(URL url)
TCS Confidential
51
Icons
Methods of Icon interface:
int getIconHeight()
int getIconWidth(),
void paintIcon(Component c,
Graphics g, int x, int y)
TCS Confidential
52
Labels
Swing labels are instances of JLabel
class, which extends JComponent
It can display text and/or icon
Some of JLabel constructors are:
JLabel(Icon i), JLabel(String s)
JLabel(String s, Icon i, int
JLabel.align)
align is LEFT, RIGHT, or, CENTER
defined as a constant in
SwingConstants interface
TCS Confidential
53
Labels
The icon and text associated
with the label can be read and
written by the following
methods:
Icon getIcon()
String getText()
void setIcon()
void setText(String s)
TCS Confidential
54
Text Fields
The Swing text field is encapsulated
by the class JTextComponent which
extends JComponent. The subclass
JTextField allows to edit one line of
text:
JTextField()
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
TCS Confidential
55
Text Fields
The JPasswordField class
creates a text field whose input
characters can be masked by
using the method
setEchoChar(char)
Text areas are implemented in
Swing with the class, JTextArea
JTextArea(int, int),
JTextArea(String, int, int)
TCS Confidential
56
Buttons
Swing buttons are subclasses of
AbstractButton, that extends
JComponent
Contains many methods that
allow control over buttons, check
boxes, and radio buttons
One can define different icons
that are displayed for the
component when it is disabled,
pressed, selected, or mouse
positioned over it
TCS Confidential
57
Buttons
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
The text associated with a button
can be read and written via
methods, getText(),
setText(String s)
TCS Confidential
58
The Buttons ...
Push buttons, check boxes, and radio
buttons are concrete subclasses of
AbstractButton
Action events are generated when
they are pressed
Listeners register and unregister for
these events via the methods:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener
al)
TCS Confidential
59
The Buttons ...
The JButton class provides the
functionality of a push button:
Some constructors are:
JButton(Icon i)
JButton(String s),
JButton(String s, Icon i)
TCS Confidential
60
The Check Boxes
The JCheckBox class provides the
functionality of a check box. Some
constructors are:
JCheckBox(Icon i), JCheckBox(String s)
JCheckBox(Icon i, boolean state)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean
state)
TCS Confidential
61
The Check Boxes
Method setSelected(boolean state)
can change the state of check box
On (de)selection, an item event is
generated
This is handled by
itemStateChanged()
Inside it, getItem() gets JCheckBox
object that generated the event
TCS Confidential
62
Radio Buttons & Choice Lists
Radio buttons are supported by
JRadioButton class with constructors
similar to JCheckBox
Radio buttons must be configured
into a group by instantiating the
ButtonGroup class
Elements (buttons or radio buttons)
are then added to it by calling
add(AbstractButton ab)
TCS Confidential
63
Radio Buttons & Choice Lists
Pressing radio button
generates action event that is
handled by actionPerformed()
method
getActionCommand() gets the
text associated with a radio
button and uses it to set the
text field
TCS Confidential
64
Radio Buttons & Choice Lists
Choice lists of AWT are one of
the implementations of
JComboBox
Items are added to it via
addItem()
setEditable(false) is used to
make it a choice list
TCS Confidential
65
Customizing GUI Components
Extend standard component
class
Add required functionalities by
Overriding methods
Adding new methods, fields
Build GUI with this components
Demo: CustomJTextFieldDemo.java
TCS Confidential
66
Look-and-Feel
View is controlled by look-and-
feel API
Deals with the presentation (the
look) and event-handling (the feel)
Each Swing component has look-
and-feel specific behavior defined
in an associated abstract class
TCS Confidential
67
Look-and-Feel
Standard look-and-feel classes
provided are concrete classes of
the abstract look-and-feel
classes
Customizable
Can be changed at runtime
TCS Confidential
68
Demo: SwingDemo.java
Use of JComboBox,
JRadioButton, ImageIcon
Use of look-and-feel
TCS Confidential
69
Summary
AWT
Applet, Graphics, Color, Font,
Controls
Swing
JApplet, ImageIcon, Jlabel,
JTextField, JButton, JCheckBox,
JRadioButton, JComboBox

You might also like