20IT301 JAVA PROGRAMMING
By
M.Mohanraj
Assistant Professor
Department of Artificial Intelligence and Data Science
Kongunadu College of Engineering
UNIT-
5
TOPICS
1 Events, Event sources, Event
classes,
2 Event Listeners, Delegation event
model
3 Handling mouse and keyboard events, Adapter classes, inner
classes.
4 The AWT class
hierarchy,
5 user interface components- labels, button, canvas,
scrollbars, text
6 components, check box, check box groups,
choices
7 lists panels – scrollpane,
dialogs
8
9
menubar, graphics
layout manager – layout manager types –boarder, grid, flow,
card and grib bag
TOPIC
S
⚫ Concepts of Applets, differences between applets and
applications
⚫ Life cycle of an applet, types of applets
⚫ Creating applets, passing parameters to applets.
⚫ Introduction to swings, limitations of AWT
⚫ components, containers
⚫ Exploring swing- JApplet, JFrame and JComponent
⚫ Icons and Labels, text fields, buttons
⚫ Check boxes, Combo boxes,RadioButton,JButton
⚫ Tabbed Panes, Scroll Panes, Trees, and Tables
Event handling
⚫For the user to interact with a GUI, the
underlying
operating system must support event handling.
1) operating systemsconstantlymonitorevents
such as keystrokes, mouse clicks, voice command,
etc.
2) operating systems sort out these events and
report them to the appropriate application
programs
3) each application program then decides
what to do in response to these events
E⚫
vent
s
An event is an object that describesa state changein
a
source.
⚫It can be generated as a consequence of a
person interacting with the elements in a
graphical user interface.
⚫Some of the activities that cause events to be
generated are pressing a button, entering a
character via the keyboard, selecting an item in a
list, and clicking the mouse.
⚫Events may also occur that are not directly
caused by
interactions with a user interface.
⚫For example, an event may be generated when a
timer expires, a counter exceeds a value, a software
or hardware failure occurs, or an operation is
completed.
⚫Events can be defined as needed and
Event sources
⚫A source is an object that generates an event.
⚫This occurs when the internal state of that object
changes
in some way.
⚫Sources may generate more than one type of event.
⚫A source must register listeners in order for the
listeners to receive notifications about a specific
type of event.
⚫Each type of event has its own registration method.
⚫General form is:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a
reference to the event listener.
⚫For example,
1.The method that registers a keyboard event
listener is
called addKeyListener().
⚫When an event occurs, all registered listeners are
notified and receive a copy of the event object. This
is known as multicasting the event.
⚫In all cases, notificationsare sent only to listeners
that
register to receive them.
⚫Some sources may allow only one listener to register.
The general form is:
public void addTypeListener(TypeListener el)
throws java.util.TooManyListenersException
Here Type is the name of the event and el is a
reference to
the event listener.
⚫When such an event occurs, the registered
listener is notified. This is known as unicasting the
⚫A source must also provide a method that allows a
listener to
unregister an interest in a specific type of event.
⚫The general form is:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event and el is a
reference to the event listener.
⚫For example, to remove a keyboard listener, you
would call
removeKeyListener( ).
⚫The methods that add or remove listeners are provided
by the source that generates events.
⚫For example, the Component class provides methods
to add
and remove keyboard and mouse event listeners.
Event classes
⚫The Event classes that represent events are at the
core of Java's event handling mechanism.
⚫Super class of the Java event class hierarchy is
EventObject, which is in java.util. for all events.
⚫Constructor is :
EventObject(Object src)
Here, src is the object that generates this event.
⚫EventObject contains two methods:
getSource( ) and
toString( ).
⚫1. The getSource( ) method returns the source
of the event. General form is :
Object getSource( )
⚫2. The toString( ) returns the string equivalent
of the event.
⚫EventObject is a superclass of all events.
⚫AWTEvent is a superclass of all AWT events
that are handled by the delegation event
model.
⚫The package java.awt.event defines several types of
events that are generated by various user
interface elements.
Event Classes in java.awt.event
⚫ActionEvent: Generatedwhen a button is pressed,a
list item is double clicked, or a menu item is selected.
⚫AdjustmentEvent: Generated when a scroll bar
is manipulated.
⚫ComponentEvent: Generated when a component is
hidden, moved, resized, or becomes visible.
⚫ContainerEvent: Generated when a component is
added to or removed from a container.
⚫FocusEvent: Generatedwhen a component gains or
loses keyboard focus.
⚫InputEvent: Abstract super class for all component
input
event classes.
⚫ItemEvent: Generated when a check box or list
item is
clicked; also
⚫occurs when a choice selection is made or a
checkable
menu item is selected or deselected.
⚫KeyEvent: Generated when input is received
from the
keyboard.
⚫MouseEvent: Generated when the mouse is
dragged, moved, clicked, pressed, or released; also
generated when the mouse enters or exits a
component.
⚫TextEvent: Generated when the value of a text area or
text
field is changed.
⚫WindowEvent: Generated when a window is
Event Listeners
⚫A listener is an object that is notified when an event
occurs.
⚫Event has two major requirements.
1. It must have been registered with one or more
sources
to receive
notifications about specific types of events.
2.It must implement methods to receive and
process these
notifications.
⚫The methods that receive and process events are
defined in
a set of interfaces found in java.awt.event.
⚫For example, the MouseMotionListener interface
defines two methods to receive notifications when
the mouse is dragged or moved.
⚫Any object may receive and process one or both of
Delegation event model
⚫The modern approach to handling events is based
on the delegation event model, which
defines standard and consistent mechanisms to
generate and process events.
⚫Its concept is quite simple: a source generates an event
and
sends it to one or more listeners.
⚫In this scheme, the listener simply waits until it
receives an
event.
⚫Once received, the listener processes the event and
then
returns.
⚫The advantage of this design is that the application
logic that processes events is cleanly separated
⚫In the delegation event model, listeners must register
with a source in order to receive an event
notification. This provides an important benefit:
notifications are sent only to listeners that want to
receive them.
⚫This is a more efficient way to handle events than the
design used by the old Java 1.0 approach. Previously,
an event was propagated up the containment
hierarchy until it was handled by a component.
⚫This required components to receive events that
they did not process, and it wasted valuable
time.The delegation event model eliminates this
overhead.
Note
⚫Java also allows you to process events without
using the delegation event model.
⚫This can be done by extending an AWT component.
Handling mouse
events
⚫ mouse events can be handled by
implementing the MouseListener and the
MouseMotionListener interfaces.
⚫ MouseListener Interface defines five methods.
The general forms of these methods are:
1. void mouseClicked(MouseEvent me)
2. void mouseEntered(MouseEvent me)
3. void mouseExited(MouseEvent me)
4. void mousePressed(MouseEvent me)
5. void mouseReleased(MouseEvent me)
⚫ MouseMotionListener Interface. This
interface defines
two methods. Their general forms are :
1. void mouseDragged(MouseEvent me)
2. void mouseMoved(MouseEvent me)
Handling keyboard events
⚫ Keyboard events, can be handled by
implementing the
KeyListener interface.
⚫ KeyListner interface defines three
methods. The general forms of these
methods are :
1. void keyPressed(KeyEvent ke)
2. void keyReleased(KeyEvent ke)
3. void keyTyped(KeyEvent ke)
⚫ To implement keyboard events implementation
to the above methods is needed.
L
3.2
Adapter classes
⚫Java provides a special feature, called an adapter
class, that
can simplify the creation of event handlers.
⚫An adapter class provides an empty implementation
of all methods in an event listener interface.
⚫Adapter classes are useful when you want to
receive and process only some of the events that
are handled by a particular event listener interface.
⚫You can define a new class to act as an event
listener by extending one of the adapter classes
and implementing only those events in which you are
interested.
Adapter classes in java.awt.event
are.
Adapter Class
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapt
er WindowAdapter
Listener
Interface
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListen
er WindowListener
Inner classes
⚫ Innerclasses, which allow oneclass to be defined within
another.
⚫ An inner class is a non-static nested class. It has access to
all of the variables and methods of its outer class and
may refer to them directly in the same way that other
non-static members of the outerclass do.
⚫ An innerclass is fullywithin the scope of its enclosing class.
⚫ an inner class has access to all of the members of its
enclosing
class, but the reverse is not true.
⚫ Members of the inner class are known only within the
scope of
the inner class and may not be used by the outer class
The AWT class hierarchy
⚫ The AWT classes are contained in the java.awt
package. It is one of Java's largest packages. some of
the AWT classes.
⚫ AWT Classes
1. AWTEvent:Encapsulates AWT events.
2. AWTEventMulticaster: Dispatches events to
multiple
listeners.
3. BorderLayout: The border layout manager.
Border layouts use five components: North,
South, East, West, and Center.
4. Button: Creates a push button control.
5. Canvas: A blank, semantics-free window.
6. CardLayout: The card layout manager. Card
layouts
emulate index cards. Only the one on top is
7. Checkbox: Creates a check box control.
8. CheckboxGroup: Creates a group of check box controls.
9. CheckboxMenuItem: Creates an on/off menu item.
10. Choice: Creates a pop-up list.
11. Color: Manages colors in a portable, platform-independent
fashion.
12. Component: An abstract super class for various AWT
components.
13. Container: A subclass of Component that can hold other
components.
14. Cursor: Encapsulates a bitmapped cursor.
15. Dialog: Creates a dialog window.
16. Dimension: Specifies the dimensions of an object. The width is
stored
in width, and the height is stored in height.
17. Event: Encapsulates events.
18. EventQueue: Queues events.
19. FileDialog: Creates a window from which a file can be
selected.
20. FlowLayout: The f low layout manager. Flow layout positions
components left to right, top to bottom.
21. Font: Encapsulates a type font.
22. FontMetrics: Encapsulates various information related to a
font. This
information helps you display text in a window.
23. Frame: Creates a standard window that has a title bar, resize
corners, and a menu bar.
24. Graphics: Encapsulates the graphics context. This context is
used by
various output methods to display output in a window.
25. GraphicsDevice: Describes a graphics device such as a screen
or
printer.
26. GraphicsEnvironment: Describes the collection of available
Font and GraphicsDevice objects.
27. GridBagConstraints: Defines various constraints relating
to the GridBagLayout class.
28. GridBagLayout: The grid bag layout manager. Grid bag layout
displays components subject to the constraints specified
by GridBagConstraints.
29. GridLayout: The grid layout manager. Grid layout
displays components in a two-dimensional
grid.
30. Scrollbar: Creates a scroll bar control.
31. ScrollPane: A container that provides horizontal and/or
vertical scrollbars for another component.
32. SystemColor: Contains the colors of GUI widgets such
as
windows, scrollbars, text, and others.
33. TextArea: Creates a multilineedit control.
34. TextComponent: A super class for TextArea and
TextField.
35. TextField: Creates a single-lineedit control.
36. Toolkit: Abstract class implemented by the AWT.
37. Window: Creates a window with no frame, no menu
bar, and
no title.
user interface components
display
s.
str
. This string is left-
justified.
⚫Labels: Creates a label that displays a string.
⚫ A label is an object of type Label, and it contains a string,
which it
⚫ Labels are passive controls that do not support any interaction
with the user.
⚫ Label defines the following constructors:
1. Label( )
2. Label(String str)
3. Label(String str, int how)
⚫ The firstversion creates a blank label.
⚫ The second version creates a label that contains the string
specified by
⚫ The third version creates a label that contains the string
specified by str using the alignment specified by how. The value
of how must be one of these three constants: Label.LEFT,
Label.RIGHT, or Label.CENTER.
⚫Set or change the text in a label is done by using
the
setText( ) method.
⚫Obtain the current label by calling getText( ).
⚫These methods are shown here:
void setText(String str)
String getText( )
⚫For setText( ), str specifies the new label. For
getText( ), the current label is returned.
⚫To set the alignment of the string within the label
by
calling setAlignment( ).
⚫To obtain the current alignment, call
getAlignment( ).
⚫ The methods are as follows:
void setAlignment(int how)
int getAlignment( )
Button
an event when it is
pressed.
that contains str as a
label.
⚫ The most widely used control is the push button.
⚫ A push button is a component that contains a label and that
generates
⚫ Push buttons are objects of type Button. Button defines these
two
constructors:
Button( )
Button(String str)
⚫ The first version creates an empty button. The second creates
a button
⚫ After a button has been created, you can set its label by calling
setLabel( ).
⚫ You can retrieve its label by calling getLabel( ).
⚫ These methods are as
follows: void
setLabel(String str) String
getLabel( )
Here, str becomes the
new label for the
Button creation: Button yes = new
Button("Yes");
canvas
⚫It is not part of the hierarchy for applet or frame
windows
⚫Canvas encapsulates a blank window upon which
you can draw.
⚫Canvas creation:
Canvas c = new Canvas();
Image test = c.createImage(200, 100);
⚫This creates an instance of Canvas and then calls the
createImage( ) method to actually make an Image
object. At this point, the image is blank.
scrollbars
⚫Scrollbar generates adjustment events when the
scroll bar
is manipulated.
⚫Scrollbar creates a scroll bar control.
⚫Scroll bars are used to select continuous values
between a
specified minimum and maximum.
⚫Scroll bars may be oriented horizontally or
vertically.
⚫A scroll bar is actuallya composite of several
individual parts.
⚫Each end has an arrow that you can click to move
the current value of the scroll bar one unit in the
direction of the arrow.
⚫The current value of the scroll bar relative to its
minimum and maximum values is indicated by the
⚫ Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
⚫ The first form creates a vertical scroll bar.
⚫ The second and third forms allow you to specify the
orientation of the scroll bar. If style is
Scrollbar.VERTICAL, a vertical scroll bar is created. If
style is Scrollbar.HORIZONTAL, the scroll bar is
horizontal.
⚫ In the third form of the constructor, the initial value of the
scroll
bar is passed in initialValue.
⚫ The number of units represented by the height of the
thumb is
passed in thumbSize.
⚫ The minimum and maximumvalues for the scroll
barare specified by min and max.
⚫ vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0,
height);
Text
⚫Text is created by Using a TextField class
⚫The TextField class implements a single-line text-
entry area, usually called an edit
⚫control.
⚫Text fields allow the user to enter strings and to
edit the
text using the arrow
⚫keys, cut and paste keys, and mouse selections.
⚫TextField is a subclass of TextComponent.
TextField
defines the following constructors:
TextField( )
TextField(int
numChars)
TextField(String str)
TextField(String str, int
⚫The first version creates a default text field.
⚫The second form creates a text field that is
numChars
characters wide.
⚫The third form initializes the text field with the
string contained in str.
⚫The fourth form initializes a text field and sets
its width.
⚫TextField (and its superclass TextComponent)
provides
several methods that allow you to utilize a text
field.
⚫To obtain the string currently contained in the
text field,
call getText().
⚫To set the text, call setText( ). These methods
are as
follows:
Components
⚫At the top of the AWT hierarchy is the Component
class.
⚫Component is an abstract class that encapsulates all
of the
attributes of a visual component.
⚫All user interface elements that are displayed on the
screen and that interact with the user are subclasses
of Component.
⚫It defines public methods that are responsible
for managing events, such as mouse and
keyboard input, positioning and sizing the
window, and repainting.
⚫A Component object is responsible for
remembering the current foreground and
⚫To add components
Component add(Component compObj)
Here, compObj is an instance of the control that you
want to add. A reference to compObj is returned.
Once a control has been added, it will
automatically be visible whenever its parent
window is displayed.
⚫To remove a control from a window when the
control is no
longer needed call remove( ).
⚫This method is also defined by Container. It
has this general form:
void remove(Component obj)
Here, obj is a reference to the control you want
to remove.
You can remove all controls by calling
removeAll( ).
check box,
⚫A check box is a control that is used to turn an option
on or off. It consists of a small box that can either
contain a check mark or not.
⚫There is a label associated with each check box that
describes what option the box represents.
⚫You can change the state of a check box by clicking on
it.
⚫Check boxes can be used individually or as part of a
group.
⚫Checkboxes are objects of the Checkbox class.
⚫ Checkbox supports these constructors:
1. Checkbox( )
2. Checkbox(String str)
3. Checkbox(String str, boolean on)
4. Checkbox(String str, boolean on, CheckboxGroup
cbGroup)
5. Checkbox(String str, CheckboxGroup cbGroup, boolean
on)
⚫ The first form creates a check box whose label is initially
blank. The
state of the check box is unchecked.
⚫ The second form creates a check box whose label is specified
by str.
The state of the check box is unchecked.
⚫ The third form allows you to set the initial state of the check
box. If on
is true, the check box is initiallychecked; otherwise, it is
cleared.
⚫ The fourth and fifth forms create a check box whose label is
specified by str and whose group is specified by cbGroup. If
this check box is not part of a group, then cbGroup must be
⚫To retrieve the current state of a check box, call
getState( ).
⚫To set its state, call setState( ).
⚫To obtain the current label associated with a check
box by calling getLabel().
⚫To set the label, call setLabel( ).
⚫These methods are as follows:
boolean getState( )
void setState(boolean
on) String getLabel( )
void setLabel(String
str)
Here, if on is true, the
box is checked. If it is
false, the box
is
cleared.
Checkbox creation:
check box groups
⚫ It is possible to create a set of mutually exclusive check boxes in
which one and
only one check box in the group can be checked at any one time.
⚫ These check boxes are oftenccalled radio buttons.
⚫ To create a set of mutually exclusive check boxes, you must first
define the group to which they will belong and then
specify that group when you constructthe check boxes.
⚫ Check box groups are objects of type CheckboxGroup. Only the
default
constructoris defined, which creates an empty group.
⚫ To determine which check box in a group is currentlyselected by
calling
getSelectedCheckbox( ).
⚫ To set a check box by calling setSelectedCheckbox( ).
⚫ These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkboxwhich)
Here, which is the check box that you want to be selected. The
previously
selected checkbox will be turned off.
⚫ CheckboxGroup cbg = new CheckboxGroup();
⚫ Win98 = new Checkbox("Windows 98", cbg, true);
⚫ winNT = new Checkbox("Windows NT", cbg, false);
choices
⚫The Choice class is used to create a pop-up list of
items
from which the user may choose.
⚫A Choice control is a form of menu.
⚫Choice only defines the default constructor, which
creates an empty list.
⚫To add a selection to the list, call addItem( ) or add(
).
void addItem(String name)
void add(String name)
⚫Here, name is the name of the item being added.
⚫Items are added to the list in the order to determine
which
item is currently selected, you may call either
getSelectedItem( ) or getSelectedIndex( ).
String
getSelectedItem( ) int
getSelectedIndex( )
lists
⚫ The List class provides a compact, multiple-choice, scrolling
selection
list.
⚫ List object can be constructed to show any number of choices
in the
visible window.
⚫ It can also be created to allow multiple selections. List provides
these
constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
⚫ To add a selection to the list, call add( ). It has the following
two forms:
void add(String name)
void add(String name, int index)
⚫ Ex
:
List os = new List(4,
true);
panels
⚫ The Panel class is a concrete subclass of Container.
⚫ It doesn't add any new methods; it simply implements
Container.
⚫ A Panel may be thought of as a recursively nestable, concrete
screen
component. Panel is the superclass for Applet.
⚫ When screen output is directed to an applet, it is drawn on the
surface
of a Panel object.
⚫ Panel is a window that does not contain a title bar,
menu bar, or border.
⚫ Components can be added to a Panel object by its add( )
method (inherited from Container). Once these components
have been added, you can position and resize them manually
using the setLocation( ), setSize( ), or setBounds( ) methods
defined by Component.
⚫ Ex: Panel osCards = new Panel();
scrollpane
⚫ A scroll pane is a component that presents a
rectangular
area in which a component may be viewed.
⚫ Horizontal and/or vertical scroll bars may be
provided if necessary.
⚫ constants are defined by the
ScrollPaneConstants
interface.
1. HORIZONTAL_SCROLLBAR_ALWAYS
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
3. VERTICAL_SCROLLBAR_ALWAYS
4. VERTICAL_SCROLLBAR_AS_NEEDED
dialogs
⚫Dialog class creates a dialog window.
⚫constructors are :
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean
mode)
⚫The dialog box allows you to choose a method that
should
be invoked when the button is clicked.
⚫Ex: Font f = new Font("Dialog", Font.PLAIN, 12);
menubar
⚫MenuBar class creates a menu bar.
⚫A top-level window can havea menu bar associated
with it. A menu bar displays a list of top-level menu
choices. Each choice is associated with a drop-down
menu.
⚫To create a menu bar, first create an instance of
MenuBar.
⚫This class only defines the default constructor. Next,
create instances of Menu that will define the
selections displayed on the bar.
⚫Following are the constructors for Menu:
Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable)
⚫Once you havecreated a menu item, you must add
the item to a Menu object by using
MenuItem add(MenuItem item)
⚫Here, item is the item being added. Items are
added to a menu in the order in which the calls to
add( ) take place.
⚫Once you have added all items to a Menu object,
you can add that object to the menu bar by using
this version of add( ) defined by MenuBar:
⚫Menu add(Menu menu)
Graphics
⚫ The AWT supports a rich assortment of graphics methods.
⚫ All graphics are drawn relative to a window.
⚫ A graphics context is encapsulated by the Graphics class
⚫ It is passed to an applet when one of its various methods, such
as paint( )
orupdate( ), is called.
⚫ It is returned by the getGraphics( ) method of Component.
⚫ The Graphics class defines a number of drawing functions.
Each shape can be drawn edge-only or filled.
⚫ Objects are drawn and filled in the currently selected graphics
color,
which is black by default.
⚫ When a graphics object is drawn that exceeds the dimensions of
the
window, output is automatically clipped
⚫ Ex:
Public void paint(Graphics g)
{
G.drawString(“welcome”,20,20);
}
Layout manager
⚫ A layout managerautomatically arrangesyour controls
within a
window by using some type of algorithm.
⚫ it is very tedious to manually lay out a large number of
componentsand sometimes the width and height
information is not yet availablewhen you need to arrange
some control, because the native toolkit components
haven't been realized.
⚫ Each Container object has a layout managerassociated
with it.
⚫ A layout manager is an instance of any class that
implements the
LayoutManager interface.
⚫ The layout manager is set by the setLayout( ) method. If
no call
Layout manager types
Layout manager class defines
the following types of layout
managers
⚫ Boarder Layout
⚫ Grid Layout
⚫ Flow Layout
⚫ Card Layout
⚫ GridBag Layout
Boarder layout
⚫ The BorderLayout class implements a common layout style for
top- level windows. It has four narrow, fixed-width components
at the edges and one large area in the center.
⚫ The four sides are referred to as north, south, east, and west.
The
middle area is called the center.
⚫ The constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
⚫ BorderLayout defines the following constants that specify the
regions:
BorderLayout.CENT
ER B
orderLayout.SOUTH
BorderLayout.EAST
B
orderLayout.WEST
BorderLayout.NORT
H
⚫ Components can be
added
Grid layout
⚫ GridLayout lays out components in a two-dimensional grid.
When you
instantiate a
⚫ GridLayout, you define the number of rows and
columns. The constructors are
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int
horz, int vert)
⚫ The first form creates a single-column grid layout.
⚫ The second form creates a grid layout
⚫ with the specified number of rows and columns.
⚫ The third form allows you to specify the horizontal and
vertical space
left between components in horz and vert, respectively.
⚫ Either numRows or numColumns can be zero. Specifying
numRows as zero allows for unlimited-length columns.
Specifying numColumns as zero allows for unlimited-
lengthrows.
Flow layout
⚫ FlowLayout is the default layout manager.
⚫ Components are laid out from the upper-left corner, left to
right and top to bottom. When no more components fit on a
line, the next one appears on the next line. A small space is
left between each component, above and below, as well as
left and right.
⚫ The constructors are
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
⚫ The first form creates the default layout, which centers
components and leaves five pixels of space between each
component.
⚫ The second form allows to specify how each line is aligned.
Valid values
for are:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment,
respectively.
Card layout
⚫ The CardLayout class is unique among the other layout
managers in that it stores several different layouts.
⚫ Each layout can be thought of as being on a separate index
card in a deck that can be shuffled so that any card is on
top at a given time.
⚫ CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
⚫ The cards are held in an object of type Panel. This panel
must have
CardLayout selected as its layout manager.
⚫ Cards are added to panel using
void add(Component panelObj, Object name);
⚫ methods defined by
CardLayout: void
first(Container deck) void
last(Container deck) void
next(Container deck)
void previous(Container
deck)
GridBag Layout
⚫The Grid bag layout displays components subject
to the constraints specified by
GridBagConstraints.
⚫GridLayout lays out components in a two-
dimensional
grid.
⚫The constructors
are GridLayout( )
GridLayout(int
numRows, int
numColumns)
Concepts of Applets
⚫ Applets are small applications that are accessed on an
Internet server, transported over the Internet,
automatically installed, and run as part of a Web
document.
⚫ After an applet arrives on the client, it has limited
access to resources, so that it can produce an arbitrary
multimedia user interface and run complex
computations without introducing the risk of viruses or
breaching data integrity.
⚫ applets – Java program that runs within a Java-enabled
browser, invoked through a “applet” reference on a web
page, dynamically downloaded to the client computer
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
There are two ways to run an applet:
1. Executing the applet within a Java-compatible Web
browser, such as NetscapeNavigator.
2. Using an applet viewer, such as the standard JDK
tool,
appletviewer.
⚫ An appletviewer executes your applet in a window.
This is generally the fastest and easiest way to test
an applet.
⚫ To execute an applet in a Web browser, you need to
write a short HTML text file that contains the
appropriate APPLET tag.
<applet code="SimpleApplet" width=200
height=60>
</applet>
Differences between applets and applications
⚫ Java can be used to create two types of programs:
applications
and applets.
⚫ An application is a program that runs on your computer,
under the operating system of that Computer(i.e an
application created by Java is moreor less like onecreated
using C or C++).
⚫ When used to createapplications, Java is not
much different
from anyother computer language.
⚫ An applet is an application designed to be transmitted
over the
Internetand executed by a Java-compatible Web browser.
⚫The important difference is that an applet is an
intelligent program, not just an animation or
media file(i.e an applet is a program that can react
to user input and dynamically change—not just run
the same animation or sound over and over.
⚫Applications require main method to execute.
⚫Applets do not require main method.
⚫Java's console input is quite limited
⚫Applets are graphical and window-based.
Life cycle of an applet
⚫
⚫
⚫ Applets life cycle includes the following methods
1. init( )
2. start( )
3. paint( )
4. stop( )
5. destroy( )
When an applet begins, the AWT calls the following
methods, in
this sequence:
init( )
start( )
paint(
)
When an
applet is
terminated,
the following
sequence of
method
calls takes
⚫ init( ): The init( ) method is the first method to be called.
This is where you should initialize variables. This method is
called only once during the run time of your applet.
⚫ start( ): The start( ) method is called after init( ). It is also
called to restart an applet after it has been stopped. Whereas
init( ) is called once—the first time an applet is loaded—start( )
is called each time an applet's HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the
applet resumes execution at start( ).
⚫ paint( ): The paint( ) method is called each time applet's output
must be redrawn. paint( ) is also called when the applet
begins execution. Whatever the cause, whenever the applet
must redraw its output, paint( ) is called. The paint( )
method has one parameter of type Graphics. This parameter
will contain the graphics context, which describes the
graphics environment in which the applet is running. This
context is used whenever output to the applet is required.
⚫ stop( ): The stop( ) method is called when a web browser
leaves the HTML document containing the applet—when it goes
to another page, for example. When stop( ) is called, the
applet is probably running. Applet uses stop( ) to suspend
threads that don't need to run when the applet is not visible. T
o
restart start( ) is called if the user returns to the page.
⚫ destroy( ): The destroy( ) method is called when the
environment determines that your applet needs to be
removed completely from memory. The stop( ) method is
always called before destroy( ).
Types of applets
⚫ Applets are two types
1.Simple applets
2.JApplets
⚫Simple applets can be created by extending
Applet class
⚫JApplets can be created by extending JApplet
class of javax.swing.JApplet package
Creating applets
⚫ Applets are created by extending the Applet class.
import java.awt.*;
import java.applet.*;
/*<appletcode="AppletSkel" width=300
height=100></applet> */
public class AppletSkel extends Applet {
public void init() {
// initialization
}
public void start() {
// start or resume execution
}
public void stop() {
// suspends execution
}
public void destroy() {
// perform shutdown activities
}
public void paint(Graphics g) {
// redisplaycontents of window
}
}
passing parameters to applets
⚫ APPLET tag in HTML allows you to pass parameters to
applet.
⚫ To retrieve a parameter, use the getParameter( ) method. It
returns
the value of the specified parameter in the form of a String
object.
// Use Parameters
import java.awt.*;
import
java.applet.*;
/*
<applet
code="ParamDem
o" width=300
height=80>
<param
name=fontName
public class ParamDemo extends
Applet{
String
fontName; int
fontSize;
f loat leading;
boolean active;
// Initialize the
string to be
displayed.
public void
start() {
String param;
fontName =
getParameter("
fontName");
if(fontName ==
null)
fontName =
"Not Found";
param =
getParameter("
fontSize");
try {
if(param != null) // if not found
fontSize =
Integer.parseInt(param); else
fontSize = 0;
} catch(NumberFormatException
e) { fontSize = -1;
}
param =
try {
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading =
0;
}
catch(Nu
mberForm
atExceptio
n e) {
leading = -
1;
}
param =
getParam
eter("acco
untEnable
d");
if(param !
= null)
active =
Boolean.v
alueOf(pa
ram).bool
eanValue(
Introduction to swings
⚫ Swing is a set of classes that provides more powerful and f
lexible
components than are possible with the AWT.
⚫ In addition to the familiar components, such as buttons, check
boxes, and labels, Swing supplies several exciting additions,
including tabbed panes, scroll panes, trees, and tables.
⚫ Even familiar components such as buttons have more
capabilities in
Swing.
⚫ For example, a button may have both an image and a text
string associated with it. Also, the image can be changed as
the state of the button changes.
⚫ Unlike AWT components, Swing components are not
implemented by
platform-specific code.
⚫ Instead, they are written entirely in Java and, therefore, are
platform-
independent.
⚫ The Swing component are defined in
javax.swing
1. AbstractButton: Abstract superclass for Swing buttons.
2. ButtonGroup: Encapsulates a mutually exclusive set of
buttons.
3. ImageIcon: Encapsulates an icon.
4. JApplet: The Swing version of Applet.
5. JButton: The Swing push button class.
6. JCheckBox: The Swing check box class.
7. JComboBox : Encapsulates a combo box (an combination
of a
drop-down list and text field).
8. JLabel: The Swing version of a label.
9. JRadioButton: The Swing version of a radio button.
10. JScrollPane: Encapsulates a scrollable window.
11. JTabbedPane: Encapsulates a tabbed window.
12. JTable: Encapsulates a table-based control.
13. JTextField: The Swing version of a text field.
14. JTree: Encapsulates a tree-based control.
Limitations of AWT
⚫AWT supports limited number of GUI components.
⚫AWT components are heavy weight components.
⚫AWT components are developed by using platform
specific
code.
⚫AWT components behaves differently in
different operating systems.
⚫AWT component is converted by the native
code of the
operating system.
⚫Lowest Common Denominator
⚫If not available natively on one Java
platform, not available on any Java
platform
⚫Simple Component Set
⚫Components Peer-Based
⚫Platform controls component appearance
⚫Inconsistencies in implementations
⚫Interfacing to native platform error-prone
components
⚫Container
⚫JComponent
⚫ AbstractButton
⚫ JButton
⚫ JMenuItem
⚫ JCheckBoxMenuItem
⚫ JMenu
⚫ JRadioButtonMenuIte
m
⚫ JToggleButton
⚫ JCheckBox
⚫ JRadioButton
Components (contd…)
⚫JComponen
t
⚫JComboBox
⚫JLabel
⚫JList
⚫JMenuBar
⚫JPanel
⚫JPopupMen
u
⚫JScrollBar
⚫JScrollPane
Components (contd…)
⚫JComponent
⚫JTextCompone
nt
⚫ JTextArea
⚫ JTextField
⚫ JPasswordFie
ld
⚫ JTextPane
⚫ JHTMLPane
Containers
⚫Top-Level Containers
⚫ Thecomponents at the top of any
Swing containment hierarchy
General Purpose Containers
⚫Intermediate containers that can be used under
many
different circumstances.
Special Purpose Container
⚫Intermediate containers that play specific roles in
the UI.
Exploring swing- JApplet
⚫If using Swing components in an applet,
subclass
JApplet, not Applet
⚫JApplet is a subclass of Applet
⚫Sets up special internal component event
handling, among other things
⚫Can have a JMenuBar
⚫Default LayoutManager is BorderLayout
JFrame
public class FrameTest {
public static void main (String args[])
{ JFrame f = new JFrame ("JFrame
Example"); Containerc =
f.getContentPane(); c.setLayout (new
FlowLayout());
for (int i = 0; i < 5; i++) {
c.add (new JButton ("No"));
c.add (new Button
("Batter"));
}
c.add (new JLabel
("Swing")); f.setSize (300,
200);
f.show();
}
JComponent
⚫ JComponent supports the following
components.
⚫ JComponent
⚫ JComboBox
⚫ JLabel
⚫ JList
⚫ JMenuBar
⚫ JPanel
⚫ JPopupMenu
⚫ JScrollBar
⚫ JScrollPane
⚫ JTextComponent
⚫ JTextArea
⚫ JTextField
⚫ JPasswordField
⚫ JTextPane
⚫ JHTMLPane
Icons and Labels
⚫ In Swing, icons are encapsulated by the ImageIcon
class, which paints an icon from an image.
⚫ constructors are:
ImageIcon(String filename)
ImageIcon(URL url)
⚫ The ImageIcon class implements the Icon
interface that declares the methods
1. int getIconHeight( )
2. intgetIconWidth( )
3. void paintIcon(Component comp,Graphics g,int x,
int y)
⚫ Swing labels are instances of the JLabel class, which
extends
JComponent.
⚫ It can display text and/or an icon.
⚫ Constructors are:
JLabel(Icon i)
Label(String
s)
JLabel(String
s, Icon i, int
align)
⚫ Here, s and i are the text and icon used for the label. The
align argument is either LEFT, RIGHT, or CENTER. These
constants are defined in the SwingConstants interface,
⚫ Methods are:
1. Icon getIcon( )
2. String getText( )
3. void setIcon(Icon i)
4. void setText(String s)
⚫ Here, i and s are the icon and text, respectively.
Text fields
⚫The Swing text field is encapsulated by the
JTextComponent class, which extendsJComponent.
⚫It provides functionality that is common to Swing
text
components.
⚫One of its subclasses is JTextField, which allows you
to
edit one line of text.
⚫ Constructors are:
JTextField( )
JTextField(intcols)
JTextField(String s, int
cols) JTextField(String s)
⚫Here, s is the string to be presented, and cols is the
number of columns in the text field.
Buttons
by the
AWT.
JComponent
.
⚫ Swing buttons provide features that are not found in the Button class
defined
⚫ Swing buttons are subclassesof the AbstractButton class, which
extends
⚫ AbstractButton contains many methods that allowyou to control the
behavior of buttons, check boxes, and radio buttons.
⚫ Methods are:
1. void setDisabledIcon(Icon di)
2. void setPressedIcon(Iconpi)
3. void setSelectedIcon(Icon si)
4. void setRolloverIcon(Icon ri)
⚫ Here, di, pi, si, and ri are the icons to be used for these different
conditions.
⚫ The text associated with a button can be read and written via the
following
methods:
1. String getText( )
2. void setText(String s)
⚫ Here, s is the text to be associated with the button.
JButton
⚫The JButton class provides the functionality of a
push
button.
⚫JButton allows an icon, a string, or both to be
associated with the push button.
⚫ Some of its constructors are :
JButton(Icon i) JButton(String s)
JButton(String s, Icon i)
⚫Here, s and i are the string and icon used for the
button.
Check boxes
⚫ The JCheckBox class, which provides the functionality of a
check box,
is a concrete implementation of AbstractButton.
⚫ Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean
state) JCheckBox(String s)
JCheckBox(String s, boolean
state) JCheckBox(String s, Icon
i)
JCheckBox(String s, Icon i,
boolean state)
⚫ Here, i is the icon for the button.
The text is specified by s. If state
is
true, the check box is initially
selected. Otherwise, it is not.
Combo boxes
⚫ Swing provides a combo box (a combination of a text field and
a drop- down list) through the JComboBox class, which
extends JComponent.
⚫ A combo box normally displays one entry. However, it can also
display a drop-down list that allows a user to select a different
entry. You can also type your selection into the text field.
⚫ Two of JComboBox's constructors are :
JComboBox( )
JComboBox(Vectorv)
⚫ Here, v is a vector that initializes the combo box.
⚫ Items are added to the list of choices via the addItem( ) method,
whose signature is:
void addItem(Object obj)
⚫ Here, obj is the object to be added to the combo box.
Radio Buttons
⚫ Radio buttons are supported by the JRadioButton class, which
is a
concrete implementation of AbstractButton.
⚫ Some of its constructors are :
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i,
boolean state)
⚫ Here, i is the icon for the button. The
text is specified by s. If state is
true, the button is initially selected.
Otherwise, it is not.
⚫ Elements are then added to the
button group via the following
method:
void add(AbstractButton ab)
Tabbed Panes
⚫ A tabbed pane is a component that appears as a group of folders in a
file
cabinet.
⚫ Each folder has a title. When a user selects a folder, its contents
becomevisible.
Only one of the folders may be selected at a time.
⚫ Tabbed panes are commonlyused for setting configuration options.
⚫ Tabbed panes are encapsulated by the JTabbedPane class, which
extends JComponent. We will use its default constructor. Tabs are
defined via the following method:
void addTab(String str, Component comp)
⚫ Here, str is the title for the tab, and comp is the component that
should be added to the tab. Typically, a JPanel ora
subclassof it is added.
⚫ The general procedureto use a tabbed pane in an applet is
outlined here:
1.Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this
method
define the
title of the tab and the component it contains.)
3.Repeat step 2 for each tab.
Scroll Panes
⚫ A scroll pane is a component that presents a rectangular area in
which a
component may be viewed. Horizontal and/orvertical scroll bars
may be provided if necessary.
⚫ Scroll panes are implemented in Swing by the JScrollPane class,
which
extends JComponent. Some of its
constructorsare :
JScrollPane(Componentcomp)
JScrollPane(intvsb, int hsb)
JScrollPane(Componentcomp, int vsb, int hsb)
⚫ Here, comp is the component to be added to
the scroll pane. vsb and hsb are
int constants that define when vertical and horizontal scroll bars for
this scroll pane areshown.
⚫ These constants are defined by the ScrollPaneConstants interface.
1. HORIZONTAL_SCROLLBAR_ALWAYS
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
3. VERTICAL_SCROLLBAR_ALWAYS
4. VERTICAL_SCROLLBAR_AS_NEEDED
⚫ Hereare the steps to follow to use a scroll pane in an applet:
1.Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the
constructorspecify thecomponent and the policies
forvertical and horizontal scroll bars.)
3.Add the scroll pane to the content pane of the applet.
Trees
⚫Data Model - TreeModel
⚫default: DefaultTreeModel
⚫getChild, getChildCount, getIndexOfChild,
getRoot, isLeaf
⚫Selection Model – TreeSelectionModel
⚫View - TreeCellRenderer
⚫getTreeCellRendererComponent
⚫Node - DefaultMutableTreeNode
Tables
⚫ A table is a component that displays rows and columns of data. You
can drag the cursoron column boundaries to resize columns.
You can also drag a column to a new position.
⚫ Tables are implemented by the JTable class, which extends
JComponent.
⚫ One of its constructors is :
JTable(Object data[ ][ ], Object colHeads[ ])
⚫ Here, data is a two-dimensional array of the information to be
presented, and
colHeads is a one-dimensional arraywith the column headings.
⚫ Hereare the steps for using a table in an applet:
1.Create a JTable object.
2. Create a JScrollPane object. (The arguments to the
constructorspecify
the table and
the policies forvertical and horizontal scroll bars.)
3.Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.

EVENT DRIVEN PROGRAMMING SWING APPLET AWT

  • 1.
    20IT301 JAVA PROGRAMMING By M.Mohanraj AssistantProfessor Department of Artificial Intelligence and Data Science Kongunadu College of Engineering
  • 2.
  • 3.
    TOPICS 1 Events, Eventsources, Event classes, 2 Event Listeners, Delegation event model 3 Handling mouse and keyboard events, Adapter classes, inner classes. 4 The AWT class hierarchy, 5 user interface components- labels, button, canvas, scrollbars, text 6 components, check box, check box groups, choices 7 lists panels – scrollpane, dialogs 8 9 menubar, graphics layout manager – layout manager types –boarder, grid, flow, card and grib bag
  • 4.
    TOPIC S ⚫ Concepts ofApplets, differences between applets and applications ⚫ Life cycle of an applet, types of applets ⚫ Creating applets, passing parameters to applets. ⚫ Introduction to swings, limitations of AWT ⚫ components, containers ⚫ Exploring swing- JApplet, JFrame and JComponent ⚫ Icons and Labels, text fields, buttons ⚫ Check boxes, Combo boxes,RadioButton,JButton ⚫ Tabbed Panes, Scroll Panes, Trees, and Tables
  • 5.
    Event handling ⚫For theuser to interact with a GUI, the underlying operating system must support event handling. 1) operating systemsconstantlymonitorevents such as keystrokes, mouse clicks, voice command, etc. 2) operating systems sort out these events and report them to the appropriate application programs 3) each application program then decides what to do in response to these events
  • 6.
    E⚫ vent s An event isan object that describesa state changein a source. ⚫It can be generated as a consequence of a person interacting with the elements in a graphical user interface. ⚫Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. ⚫Events may also occur that are not directly caused by interactions with a user interface. ⚫For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. ⚫Events can be defined as needed and
  • 7.
    Event sources ⚫A sourceis an object that generates an event. ⚫This occurs when the internal state of that object changes in some way. ⚫Sources may generate more than one type of event. ⚫A source must register listeners in order for the listeners to receive notifications about a specific type of event. ⚫Each type of event has its own registration method. ⚫General form is: public void addTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. ⚫For example, 1.The method that registers a keyboard event listener is called addKeyListener().
  • 8.
    ⚫When an eventoccurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. ⚫In all cases, notificationsare sent only to listeners that register to receive them. ⚫Some sources may allow only one listener to register. The general form is: public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException Here Type is the name of the event and el is a reference to the event listener. ⚫When such an event occurs, the registered listener is notified. This is known as unicasting the
  • 9.
    ⚫A source mustalso provide a method that allows a listener to unregister an interest in a specific type of event. ⚫The general form is: public void removeTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. ⚫For example, to remove a keyboard listener, you would call removeKeyListener( ). ⚫The methods that add or remove listeners are provided by the source that generates events. ⚫For example, the Component class provides methods to add and remove keyboard and mouse event listeners.
  • 10.
    Event classes ⚫The Eventclasses that represent events are at the core of Java's event handling mechanism. ⚫Super class of the Java event class hierarchy is EventObject, which is in java.util. for all events. ⚫Constructor is : EventObject(Object src) Here, src is the object that generates this event. ⚫EventObject contains two methods: getSource( ) and toString( ). ⚫1. The getSource( ) method returns the source of the event. General form is : Object getSource( ) ⚫2. The toString( ) returns the string equivalent of the event.
  • 11.
    ⚫EventObject is asuperclass of all events. ⚫AWTEvent is a superclass of all AWT events that are handled by the delegation event model. ⚫The package java.awt.event defines several types of events that are generated by various user interface elements.
  • 12.
    Event Classes injava.awt.event ⚫ActionEvent: Generatedwhen a button is pressed,a list item is double clicked, or a menu item is selected. ⚫AdjustmentEvent: Generated when a scroll bar is manipulated. ⚫ComponentEvent: Generated when a component is hidden, moved, resized, or becomes visible. ⚫ContainerEvent: Generated when a component is added to or removed from a container. ⚫FocusEvent: Generatedwhen a component gains or loses keyboard focus.
  • 13.
    ⚫InputEvent: Abstract superclass for all component input event classes. ⚫ItemEvent: Generated when a check box or list item is clicked; also ⚫occurs when a choice selection is made or a checkable menu item is selected or deselected. ⚫KeyEvent: Generated when input is received from the keyboard. ⚫MouseEvent: Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. ⚫TextEvent: Generated when the value of a text area or text field is changed. ⚫WindowEvent: Generated when a window is
  • 14.
    Event Listeners ⚫A listeneris an object that is notified when an event occurs. ⚫Event has two major requirements. 1. It must have been registered with one or more sources to receive notifications about specific types of events. 2.It must implement methods to receive and process these notifications. ⚫The methods that receive and process events are defined in a set of interfaces found in java.awt.event. ⚫For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. ⚫Any object may receive and process one or both of
  • 15.
    Delegation event model ⚫Themodern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. ⚫Its concept is quite simple: a source generates an event and sends it to one or more listeners. ⚫In this scheme, the listener simply waits until it receives an event. ⚫Once received, the listener processes the event and then returns. ⚫The advantage of this design is that the application logic that processes events is cleanly separated
  • 16.
    ⚫In the delegationevent model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. ⚫This is a more efficient way to handle events than the design used by the old Java 1.0 approach. Previously, an event was propagated up the containment hierarchy until it was handled by a component. ⚫This required components to receive events that they did not process, and it wasted valuable time.The delegation event model eliminates this overhead. Note ⚫Java also allows you to process events without using the delegation event model. ⚫This can be done by extending an AWT component.
  • 17.
    Handling mouse events ⚫ mouseevents can be handled by implementing the MouseListener and the MouseMotionListener interfaces. ⚫ MouseListener Interface defines five methods. The general forms of these methods are: 1. void mouseClicked(MouseEvent me) 2. void mouseEntered(MouseEvent me) 3. void mouseExited(MouseEvent me) 4. void mousePressed(MouseEvent me) 5. void mouseReleased(MouseEvent me) ⚫ MouseMotionListener Interface. This interface defines two methods. Their general forms are : 1. void mouseDragged(MouseEvent me) 2. void mouseMoved(MouseEvent me)
  • 18.
    Handling keyboard events ⚫Keyboard events, can be handled by implementing the KeyListener interface. ⚫ KeyListner interface defines three methods. The general forms of these methods are : 1. void keyPressed(KeyEvent ke) 2. void keyReleased(KeyEvent ke) 3. void keyTyped(KeyEvent ke) ⚫ To implement keyboard events implementation to the above methods is needed. L 3.2
  • 19.
    Adapter classes ⚫Java providesa special feature, called an adapter class, that can simplify the creation of event handlers. ⚫An adapter class provides an empty implementation of all methods in an event listener interface. ⚫Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. ⚫You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.
  • 20.
    Adapter classes injava.awt.event are. Adapter Class ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapt er WindowAdapter Listener Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListen er WindowListener
  • 21.
    Inner classes ⚫ Innerclasses,which allow oneclass to be defined within another. ⚫ An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outerclass do. ⚫ An innerclass is fullywithin the scope of its enclosing class. ⚫ an inner class has access to all of the members of its enclosing class, but the reverse is not true. ⚫ Members of the inner class are known only within the scope of the inner class and may not be used by the outer class
  • 22.
    The AWT classhierarchy ⚫ The AWT classes are contained in the java.awt package. It is one of Java's largest packages. some of the AWT classes. ⚫ AWT Classes 1. AWTEvent:Encapsulates AWT events. 2. AWTEventMulticaster: Dispatches events to multiple listeners. 3. BorderLayout: The border layout manager. Border layouts use five components: North, South, East, West, and Center. 4. Button: Creates a push button control. 5. Canvas: A blank, semantics-free window. 6. CardLayout: The card layout manager. Card layouts emulate index cards. Only the one on top is
  • 23.
    7. Checkbox: Createsa check box control. 8. CheckboxGroup: Creates a group of check box controls. 9. CheckboxMenuItem: Creates an on/off menu item. 10. Choice: Creates a pop-up list. 11. Color: Manages colors in a portable, platform-independent fashion. 12. Component: An abstract super class for various AWT components. 13. Container: A subclass of Component that can hold other components. 14. Cursor: Encapsulates a bitmapped cursor. 15. Dialog: Creates a dialog window. 16. Dimension: Specifies the dimensions of an object. The width is stored in width, and the height is stored in height. 17. Event: Encapsulates events. 18. EventQueue: Queues events. 19. FileDialog: Creates a window from which a file can be selected. 20. FlowLayout: The f low layout manager. Flow layout positions components left to right, top to bottom.
  • 24.
    21. Font: Encapsulatesa type font. 22. FontMetrics: Encapsulates various information related to a font. This information helps you display text in a window. 23. Frame: Creates a standard window that has a title bar, resize corners, and a menu bar. 24. Graphics: Encapsulates the graphics context. This context is used by various output methods to display output in a window. 25. GraphicsDevice: Describes a graphics device such as a screen or printer. 26. GraphicsEnvironment: Describes the collection of available Font and GraphicsDevice objects. 27. GridBagConstraints: Defines various constraints relating to the GridBagLayout class. 28. GridBagLayout: The grid bag layout manager. Grid bag layout displays components subject to the constraints specified by GridBagConstraints. 29. GridLayout: The grid layout manager. Grid layout displays components in a two-dimensional grid.
  • 25.
    30. Scrollbar: Createsa scroll bar control. 31. ScrollPane: A container that provides horizontal and/or vertical scrollbars for another component. 32. SystemColor: Contains the colors of GUI widgets such as windows, scrollbars, text, and others. 33. TextArea: Creates a multilineedit control. 34. TextComponent: A super class for TextArea and TextField. 35. TextField: Creates a single-lineedit control. 36. Toolkit: Abstract class implemented by the AWT. 37. Window: Creates a window with no frame, no menu bar, and no title.
  • 26.
    user interface components display s. str .This string is left- justified. ⚫Labels: Creates a label that displays a string. ⚫ A label is an object of type Label, and it contains a string, which it ⚫ Labels are passive controls that do not support any interaction with the user. ⚫ Label defines the following constructors: 1. Label( ) 2. Label(String str) 3. Label(String str, int how) ⚫ The firstversion creates a blank label. ⚫ The second version creates a label that contains the string specified by ⚫ The third version creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.
  • 27.
    ⚫Set or changethe text in a label is done by using the setText( ) method. ⚫Obtain the current label by calling getText( ). ⚫These methods are shown here: void setText(String str) String getText( ) ⚫For setText( ), str specifies the new label. For getText( ), the current label is returned. ⚫To set the alignment of the string within the label by calling setAlignment( ). ⚫To obtain the current alignment, call getAlignment( ). ⚫ The methods are as follows: void setAlignment(int how) int getAlignment( )
  • 28.
    Button an event whenit is pressed. that contains str as a label. ⚫ The most widely used control is the push button. ⚫ A push button is a component that contains a label and that generates ⚫ Push buttons are objects of type Button. Button defines these two constructors: Button( ) Button(String str) ⚫ The first version creates an empty button. The second creates a button ⚫ After a button has been created, you can set its label by calling setLabel( ). ⚫ You can retrieve its label by calling getLabel( ). ⚫ These methods are as follows: void setLabel(String str) String getLabel( ) Here, str becomes the new label for the Button creation: Button yes = new Button("Yes");
  • 29.
    canvas ⚫It is notpart of the hierarchy for applet or frame windows ⚫Canvas encapsulates a blank window upon which you can draw. ⚫Canvas creation: Canvas c = new Canvas(); Image test = c.createImage(200, 100); ⚫This creates an instance of Canvas and then calls the createImage( ) method to actually make an Image object. At this point, the image is blank.
  • 30.
    scrollbars ⚫Scrollbar generates adjustmentevents when the scroll bar is manipulated. ⚫Scrollbar creates a scroll bar control. ⚫Scroll bars are used to select continuous values between a specified minimum and maximum. ⚫Scroll bars may be oriented horizontally or vertically. ⚫A scroll bar is actuallya composite of several individual parts. ⚫Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. ⚫The current value of the scroll bar relative to its minimum and maximum values is indicated by the
  • 31.
    ⚫ Scrollbar definesthe following constructors: Scrollbar( ) Scrollbar(int style) Scrollbar(int style, int initialValue, int thumbSize, int min, int max) ⚫ The first form creates a vertical scroll bar. ⚫ The second and third forms allow you to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal. ⚫ In the third form of the constructor, the initial value of the scroll bar is passed in initialValue. ⚫ The number of units represented by the height of the thumb is passed in thumbSize. ⚫ The minimum and maximumvalues for the scroll barare specified by min and max. ⚫ vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, height);
  • 32.
    Text ⚫Text is createdby Using a TextField class ⚫The TextField class implements a single-line text- entry area, usually called an edit ⚫control. ⚫Text fields allow the user to enter strings and to edit the text using the arrow ⚫keys, cut and paste keys, and mouse selections. ⚫TextField is a subclass of TextComponent. TextField defines the following constructors: TextField( ) TextField(int numChars) TextField(String str) TextField(String str, int
  • 33.
    ⚫The first versioncreates a default text field. ⚫The second form creates a text field that is numChars characters wide. ⚫The third form initializes the text field with the string contained in str. ⚫The fourth form initializes a text field and sets its width. ⚫TextField (and its superclass TextComponent) provides several methods that allow you to utilize a text field. ⚫To obtain the string currently contained in the text field, call getText(). ⚫To set the text, call setText( ). These methods are as follows:
  • 34.
    Components ⚫At the topof the AWT hierarchy is the Component class. ⚫Component is an abstract class that encapsulates all of the attributes of a visual component. ⚫All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. ⚫It defines public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. ⚫A Component object is responsible for remembering the current foreground and
  • 35.
    ⚫To add components Componentadd(Component compObj) Here, compObj is an instance of the control that you want to add. A reference to compObj is returned. Once a control has been added, it will automatically be visible whenever its parent window is displayed. ⚫To remove a control from a window when the control is no longer needed call remove( ). ⚫This method is also defined by Container. It has this general form: void remove(Component obj) Here, obj is a reference to the control you want to remove. You can remove all controls by calling removeAll( ).
  • 36.
    check box, ⚫A checkbox is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. ⚫There is a label associated with each check box that describes what option the box represents. ⚫You can change the state of a check box by clicking on it. ⚫Check boxes can be used individually or as part of a group. ⚫Checkboxes are objects of the Checkbox class.
  • 37.
    ⚫ Checkbox supportsthese constructors: 1. Checkbox( ) 2. Checkbox(String str) 3. Checkbox(String str, boolean on) 4. Checkbox(String str, boolean on, CheckboxGroup cbGroup) 5. Checkbox(String str, CheckboxGroup cbGroup, boolean on) ⚫ The first form creates a check box whose label is initially blank. The state of the check box is unchecked. ⚫ The second form creates a check box whose label is specified by str. The state of the check box is unchecked. ⚫ The third form allows you to set the initial state of the check box. If on is true, the check box is initiallychecked; otherwise, it is cleared. ⚫ The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by cbGroup. If this check box is not part of a group, then cbGroup must be
  • 38.
    ⚫To retrieve thecurrent state of a check box, call getState( ). ⚫To set its state, call setState( ). ⚫To obtain the current label associated with a check box by calling getLabel(). ⚫To set the label, call setLabel( ). ⚫These methods are as follows: boolean getState( ) void setState(boolean on) String getLabel( ) void setLabel(String str) Here, if on is true, the box is checked. If it is false, the box is cleared. Checkbox creation:
  • 39.
    check box groups ⚫It is possible to create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. ⚫ These check boxes are oftenccalled radio buttons. ⚫ To create a set of mutually exclusive check boxes, you must first define the group to which they will belong and then specify that group when you constructthe check boxes. ⚫ Check box groups are objects of type CheckboxGroup. Only the default constructoris defined, which creates an empty group. ⚫ To determine which check box in a group is currentlyselected by calling getSelectedCheckbox( ). ⚫ To set a check box by calling setSelectedCheckbox( ). ⚫ These methods are as follows: Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkboxwhich) Here, which is the check box that you want to be selected. The previously selected checkbox will be turned off. ⚫ CheckboxGroup cbg = new CheckboxGroup(); ⚫ Win98 = new Checkbox("Windows 98", cbg, true); ⚫ winNT = new Checkbox("Windows NT", cbg, false);
  • 40.
    choices ⚫The Choice classis used to create a pop-up list of items from which the user may choose. ⚫A Choice control is a form of menu. ⚫Choice only defines the default constructor, which creates an empty list. ⚫To add a selection to the list, call addItem( ) or add( ). void addItem(String name) void add(String name) ⚫Here, name is the name of the item being added. ⚫Items are added to the list in the order to determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ). String getSelectedItem( ) int getSelectedIndex( )
  • 41.
    lists ⚫ The Listclass provides a compact, multiple-choice, scrolling selection list. ⚫ List object can be constructed to show any number of choices in the visible window. ⚫ It can also be created to allow multiple selections. List provides these constructors: List( ) List(int numRows) List(int numRows, boolean multipleSelect) ⚫ To add a selection to the list, call add( ). It has the following two forms: void add(String name) void add(String name, int index) ⚫ Ex : List os = new List(4, true);
  • 42.
    panels ⚫ The Panelclass is a concrete subclass of Container. ⚫ It doesn't add any new methods; it simply implements Container. ⚫ A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. ⚫ When screen output is directed to an applet, it is drawn on the surface of a Panel object. ⚫ Panel is a window that does not contain a title bar, menu bar, or border. ⚫ Components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component. ⚫ Ex: Panel osCards = new Panel();
  • 43.
    scrollpane ⚫ A scrollpane is a component that presents a rectangular area in which a component may be viewed. ⚫ Horizontal and/or vertical scroll bars may be provided if necessary. ⚫ constants are defined by the ScrollPaneConstants interface. 1. HORIZONTAL_SCROLLBAR_ALWAYS 2. HORIZONTAL_SCROLLBAR_AS_NEEDED 3. VERTICAL_SCROLLBAR_ALWAYS 4. VERTICAL_SCROLLBAR_AS_NEEDED
  • 44.
    dialogs ⚫Dialog class createsa dialog window. ⚫constructors are : Dialog(Frame parentWindow, boolean mode) Dialog(Frame parentWindow, String title, boolean mode) ⚫The dialog box allows you to choose a method that should be invoked when the button is clicked. ⚫Ex: Font f = new Font("Dialog", Font.PLAIN, 12);
  • 45.
    menubar ⚫MenuBar class createsa menu bar. ⚫A top-level window can havea menu bar associated with it. A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-down menu. ⚫To create a menu bar, first create an instance of MenuBar. ⚫This class only defines the default constructor. Next, create instances of Menu that will define the selections displayed on the bar. ⚫Following are the constructors for Menu: Menu( ) Menu(String optionName) Menu(String optionName, boolean removable)
  • 46.
    ⚫Once you havecreateda menu item, you must add the item to a Menu object by using MenuItem add(MenuItem item) ⚫Here, item is the item being added. Items are added to a menu in the order in which the calls to add( ) take place. ⚫Once you have added all items to a Menu object, you can add that object to the menu bar by using this version of add( ) defined by MenuBar: ⚫Menu add(Menu menu)
  • 47.
    Graphics ⚫ The AWTsupports a rich assortment of graphics methods. ⚫ All graphics are drawn relative to a window. ⚫ A graphics context is encapsulated by the Graphics class ⚫ It is passed to an applet when one of its various methods, such as paint( ) orupdate( ), is called. ⚫ It is returned by the getGraphics( ) method of Component. ⚫ The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. ⚫ Objects are drawn and filled in the currently selected graphics color, which is black by default. ⚫ When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped ⚫ Ex: Public void paint(Graphics g) { G.drawString(“welcome”,20,20); }
  • 48.
    Layout manager ⚫ Alayout managerautomatically arrangesyour controls within a window by using some type of algorithm. ⚫ it is very tedious to manually lay out a large number of componentsand sometimes the width and height information is not yet availablewhen you need to arrange some control, because the native toolkit components haven't been realized. ⚫ Each Container object has a layout managerassociated with it. ⚫ A layout manager is an instance of any class that implements the LayoutManager interface. ⚫ The layout manager is set by the setLayout( ) method. If no call
  • 49.
    Layout manager types Layoutmanager class defines the following types of layout managers ⚫ Boarder Layout ⚫ Grid Layout ⚫ Flow Layout ⚫ Card Layout ⚫ GridBag Layout
  • 50.
    Boarder layout ⚫ TheBorderLayout class implements a common layout style for top- level windows. It has four narrow, fixed-width components at the edges and one large area in the center. ⚫ The four sides are referred to as north, south, east, and west. The middle area is called the center. ⚫ The constructors defined by BorderLayout: BorderLayout( ) BorderLayout(int horz, int vert) ⚫ BorderLayout defines the following constants that specify the regions: BorderLayout.CENT ER B orderLayout.SOUTH BorderLayout.EAST B orderLayout.WEST BorderLayout.NORT H ⚫ Components can be added
  • 51.
    Grid layout ⚫ GridLayoutlays out components in a two-dimensional grid. When you instantiate a ⚫ GridLayout, you define the number of rows and columns. The constructors are GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert) ⚫ The first form creates a single-column grid layout. ⚫ The second form creates a grid layout ⚫ with the specified number of rows and columns. ⚫ The third form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. ⚫ Either numRows or numColumns can be zero. Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero allows for unlimited- lengthrows.
  • 52.
    Flow layout ⚫ FlowLayoutis the default layout manager. ⚫ Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line, the next one appears on the next line. A small space is left between each component, above and below, as well as left and right. ⚫ The constructors are FlowLayout( ) FlowLayout(int how) FlowLayout(int how, int horz, int vert) ⚫ The first form creates the default layout, which centers components and leaves five pixels of space between each component. ⚫ The second form allows to specify how each line is aligned. Valid values for are: FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT These values specify left, center, and right alignment, respectively.
  • 53.
    Card layout ⚫ TheCardLayout class is unique among the other layout managers in that it stores several different layouts. ⚫ Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. ⚫ CardLayout provides these two constructors: CardLayout( ) CardLayout(int horz, int vert) ⚫ The cards are held in an object of type Panel. This panel must have CardLayout selected as its layout manager. ⚫ Cards are added to panel using void add(Component panelObj, Object name); ⚫ methods defined by CardLayout: void first(Container deck) void last(Container deck) void next(Container deck) void previous(Container deck)
  • 54.
    GridBag Layout ⚫The Gridbag layout displays components subject to the constraints specified by GridBagConstraints. ⚫GridLayout lays out components in a two- dimensional grid. ⚫The constructors are GridLayout( ) GridLayout(int numRows, int numColumns)
  • 55.
    Concepts of Applets ⚫Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. ⚫ After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity. ⚫ applets – Java program that runs within a Java-enabled browser, invoked through a “applet” reference on a web page, dynamically downloaded to the client computer import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); }
  • 56.
    There are twoways to run an applet: 1. Executing the applet within a Java-compatible Web browser, such as NetscapeNavigator. 2. Using an applet viewer, such as the standard JDK tool, appletviewer. ⚫ An appletviewer executes your applet in a window. This is generally the fastest and easiest way to test an applet. ⚫ To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. <applet code="SimpleApplet" width=200 height=60> </applet>
  • 57.
    Differences between appletsand applications ⚫ Java can be used to create two types of programs: applications and applets. ⚫ An application is a program that runs on your computer, under the operating system of that Computer(i.e an application created by Java is moreor less like onecreated using C or C++). ⚫ When used to createapplications, Java is not much different from anyother computer language. ⚫ An applet is an application designed to be transmitted over the Internetand executed by a Java-compatible Web browser.
  • 58.
    ⚫The important differenceis that an applet is an intelligent program, not just an animation or media file(i.e an applet is a program that can react to user input and dynamically change—not just run the same animation or sound over and over. ⚫Applications require main method to execute. ⚫Applets do not require main method. ⚫Java's console input is quite limited ⚫Applets are graphical and window-based.
  • 59.
    Life cycle ofan applet ⚫ ⚫ ⚫ Applets life cycle includes the following methods 1. init( ) 2. start( ) 3. paint( ) 4. stop( ) 5. destroy( ) When an applet begins, the AWT calls the following methods, in this sequence: init( ) start( ) paint( ) When an applet is terminated, the following sequence of method calls takes
  • 60.
    ⚫ init( ):The init( ) method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet. ⚫ start( ): The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet's HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ). ⚫ paint( ): The paint( ) method is called each time applet's output must be redrawn. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. ⚫ stop( ): The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. Applet uses stop( ) to suspend threads that don't need to run when the applet is not visible. T o restart start( ) is called if the user returns to the page. ⚫ destroy( ): The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. The stop( ) method is always called before destroy( ).
  • 61.
    Types of applets ⚫Applets are two types 1.Simple applets 2.JApplets ⚫Simple applets can be created by extending Applet class ⚫JApplets can be created by extending JApplet class of javax.swing.JApplet package
  • 62.
    Creating applets ⚫ Appletsare created by extending the Applet class. import java.awt.*; import java.applet.*; /*<appletcode="AppletSkel" width=300 height=100></applet> */ public class AppletSkel extends Applet { public void init() { // initialization } public void start() { // start or resume execution } public void stop() { // suspends execution } public void destroy() { // perform shutdown activities } public void paint(Graphics g) { // redisplaycontents of window } }
  • 63.
    passing parameters toapplets ⚫ APPLET tag in HTML allows you to pass parameters to applet. ⚫ To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified parameter in the form of a String object. // Use Parameters import java.awt.*; import java.applet.*; /* <applet code="ParamDem o" width=300 height=80> <param name=fontName
  • 64.
    public class ParamDemoextends Applet{ String fontName; int fontSize; f loat leading; boolean active; // Initialize the string to be displayed. public void start() { String param; fontName = getParameter(" fontName"); if(fontName == null) fontName = "Not Found"; param = getParameter(" fontSize"); try { if(param != null) // if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) { fontSize = -1; } param =
  • 65.
    try { if(param !=null) // if not found leading = Float.valueOf(param).floatValue(); else leading = 0; } catch(Nu mberForm atExceptio n e) { leading = - 1; } param = getParam eter("acco untEnable d"); if(param ! = null) active = Boolean.v alueOf(pa ram).bool eanValue(
  • 66.
    Introduction to swings ⚫Swing is a set of classes that provides more powerful and f lexible components than are possible with the AWT. ⚫ In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables. ⚫ Even familiar components such as buttons have more capabilities in Swing. ⚫ For example, a button may have both an image and a text string associated with it. Also, the image can be changed as the state of the button changes. ⚫ Unlike AWT components, Swing components are not implemented by platform-specific code. ⚫ Instead, they are written entirely in Java and, therefore, are platform- independent.
  • 67.
    ⚫ The Swingcomponent are defined in javax.swing 1. AbstractButton: Abstract superclass for Swing buttons. 2. ButtonGroup: Encapsulates a mutually exclusive set of buttons. 3. ImageIcon: Encapsulates an icon. 4. JApplet: The Swing version of Applet. 5. JButton: The Swing push button class. 6. JCheckBox: The Swing check box class. 7. JComboBox : Encapsulates a combo box (an combination of a drop-down list and text field). 8. JLabel: The Swing version of a label. 9. JRadioButton: The Swing version of a radio button. 10. JScrollPane: Encapsulates a scrollable window. 11. JTabbedPane: Encapsulates a tabbed window. 12. JTable: Encapsulates a table-based control. 13. JTextField: The Swing version of a text field. 14. JTree: Encapsulates a tree-based control.
  • 68.
    Limitations of AWT ⚫AWTsupports limited number of GUI components. ⚫AWT components are heavy weight components. ⚫AWT components are developed by using platform specific code. ⚫AWT components behaves differently in different operating systems. ⚫AWT component is converted by the native code of the operating system.
  • 69.
    ⚫Lowest Common Denominator ⚫Ifnot available natively on one Java platform, not available on any Java platform ⚫Simple Component Set ⚫Components Peer-Based ⚫Platform controls component appearance ⚫Inconsistencies in implementations ⚫Interfacing to native platform error-prone
  • 70.
    components ⚫Container ⚫JComponent ⚫ AbstractButton ⚫ JButton ⚫JMenuItem ⚫ JCheckBoxMenuItem ⚫ JMenu ⚫ JRadioButtonMenuIte m ⚫ JToggleButton ⚫ JCheckBox ⚫ JRadioButton
  • 71.
  • 72.
    Components (contd…) ⚫JComponent ⚫JTextCompone nt ⚫ JTextArea ⚫JTextField ⚫ JPasswordFie ld ⚫ JTextPane ⚫ JHTMLPane
  • 73.
    Containers ⚫Top-Level Containers ⚫ Thecomponentsat the top of any Swing containment hierarchy
  • 74.
    General Purpose Containers ⚫Intermediatecontainers that can be used under many different circumstances.
  • 75.
    Special Purpose Container ⚫Intermediatecontainers that play specific roles in the UI.
  • 76.
    Exploring swing- JApplet ⚫Ifusing Swing components in an applet, subclass JApplet, not Applet ⚫JApplet is a subclass of Applet ⚫Sets up special internal component event handling, among other things ⚫Can have a JMenuBar ⚫Default LayoutManager is BorderLayout
  • 77.
    JFrame public class FrameTest{ public static void main (String args[]) { JFrame f = new JFrame ("JFrame Example"); Containerc = f.getContentPane(); c.setLayout (new FlowLayout()); for (int i = 0; i < 5; i++) { c.add (new JButton ("No")); c.add (new Button ("Batter")); } c.add (new JLabel ("Swing")); f.setSize (300, 200); f.show(); }
  • 78.
    JComponent ⚫ JComponent supportsthe following components. ⚫ JComponent ⚫ JComboBox ⚫ JLabel ⚫ JList ⚫ JMenuBar ⚫ JPanel ⚫ JPopupMenu ⚫ JScrollBar ⚫ JScrollPane ⚫ JTextComponent ⚫ JTextArea ⚫ JTextField ⚫ JPasswordField ⚫ JTextPane ⚫ JHTMLPane
  • 79.
    Icons and Labels ⚫In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. ⚫ constructors are: ImageIcon(String filename) ImageIcon(URL url) ⚫ The ImageIcon class implements the Icon interface that declares the methods 1. int getIconHeight( ) 2. intgetIconWidth( ) 3. void paintIcon(Component comp,Graphics g,int x, int y)
  • 80.
    ⚫ Swing labelsare instances of the JLabel class, which extends JComponent. ⚫ It can display text and/or an icon. ⚫ Constructors are: JLabel(Icon i) Label(String s) JLabel(String s, Icon i, int align) ⚫ Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, or CENTER. These constants are defined in the SwingConstants interface, ⚫ Methods are: 1. Icon getIcon( ) 2. String getText( ) 3. void setIcon(Icon i) 4. void setText(String s) ⚫ Here, i and s are the icon and text, respectively.
  • 81.
    Text fields ⚫The Swingtext field is encapsulated by the JTextComponent class, which extendsJComponent. ⚫It provides functionality that is common to Swing text components. ⚫One of its subclasses is JTextField, which allows you to edit one line of text. ⚫ Constructors are: JTextField( ) JTextField(intcols) JTextField(String s, int cols) JTextField(String s) ⚫Here, s is the string to be presented, and cols is the number of columns in the text field.
  • 82.
    Buttons by the AWT. JComponent . ⚫ Swingbuttons provide features that are not found in the Button class defined ⚫ Swing buttons are subclassesof the AbstractButton class, which extends ⚫ AbstractButton contains many methods that allowyou to control the behavior of buttons, check boxes, and radio buttons. ⚫ Methods are: 1. void setDisabledIcon(Icon di) 2. void setPressedIcon(Iconpi) 3. void setSelectedIcon(Icon si) 4. void setRolloverIcon(Icon ri) ⚫ Here, di, pi, si, and ri are the icons to be used for these different conditions. ⚫ The text associated with a button can be read and written via the following methods: 1. String getText( ) 2. void setText(String s) ⚫ Here, s is the text to be associated with the button.
  • 83.
    JButton ⚫The JButton classprovides the functionality of a push button. ⚫JButton allows an icon, a string, or both to be associated with the push button. ⚫ Some of its constructors are : JButton(Icon i) JButton(String s) JButton(String s, Icon i) ⚫Here, s and i are the string and icon used for the button.
  • 84.
    Check boxes ⚫ TheJCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton. ⚫ Some of its constructors are shown here: JCheckBox(Icon i) JCheckBox(Icon i, boolean state) JCheckBox(String s) JCheckBox(String s, boolean state) JCheckBox(String s, Icon i) JCheckBox(String s, Icon i, boolean state) ⚫ Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially selected. Otherwise, it is not.
  • 85.
    Combo boxes ⚫ Swingprovides a combo box (a combination of a text field and a drop- down list) through the JComboBox class, which extends JComponent. ⚫ A combo box normally displays one entry. However, it can also display a drop-down list that allows a user to select a different entry. You can also type your selection into the text field. ⚫ Two of JComboBox's constructors are : JComboBox( ) JComboBox(Vectorv) ⚫ Here, v is a vector that initializes the combo box. ⚫ Items are added to the list of choices via the addItem( ) method, whose signature is: void addItem(Object obj) ⚫ Here, obj is the object to be added to the combo box.
  • 86.
    Radio Buttons ⚫ Radiobuttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton. ⚫ Some of its constructors are : JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s) JRadioButton(String s, boolean state) JRadioButton(String s, Icon i) JRadioButton(String s, Icon i, boolean state) ⚫ Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected. Otherwise, it is not. ⚫ Elements are then added to the button group via the following method: void add(AbstractButton ab)
  • 87.
    Tabbed Panes ⚫ Atabbed pane is a component that appears as a group of folders in a file cabinet. ⚫ Each folder has a title. When a user selects a folder, its contents becomevisible. Only one of the folders may be selected at a time. ⚫ Tabbed panes are commonlyused for setting configuration options. ⚫ Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent. We will use its default constructor. Tabs are defined via the following method: void addTab(String str, Component comp) ⚫ Here, str is the title for the tab, and comp is the component that should be added to the tab. Typically, a JPanel ora subclassof it is added. ⚫ The general procedureto use a tabbed pane in an applet is outlined here: 1.Create a JTabbedPane object. 2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of the tab and the component it contains.) 3.Repeat step 2 for each tab.
  • 88.
    Scroll Panes ⚫ Ascroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/orvertical scroll bars may be provided if necessary. ⚫ Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent. Some of its constructorsare : JScrollPane(Componentcomp) JScrollPane(intvsb, int hsb) JScrollPane(Componentcomp, int vsb, int hsb) ⚫ Here, comp is the component to be added to the scroll pane. vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll pane areshown. ⚫ These constants are defined by the ScrollPaneConstants interface. 1. HORIZONTAL_SCROLLBAR_ALWAYS 2. HORIZONTAL_SCROLLBAR_AS_NEEDED 3. VERTICAL_SCROLLBAR_ALWAYS 4. VERTICAL_SCROLLBAR_AS_NEEDED ⚫ Hereare the steps to follow to use a scroll pane in an applet: 1.Create a JComponent object. 2. Create a JScrollPane object. (The arguments to the constructorspecify thecomponent and the policies forvertical and horizontal scroll bars.) 3.Add the scroll pane to the content pane of the applet.
  • 89.
    Trees ⚫Data Model -TreeModel ⚫default: DefaultTreeModel ⚫getChild, getChildCount, getIndexOfChild, getRoot, isLeaf ⚫Selection Model – TreeSelectionModel ⚫View - TreeCellRenderer ⚫getTreeCellRendererComponent ⚫Node - DefaultMutableTreeNode
  • 90.
    Tables ⚫ A tableis a component that displays rows and columns of data. You can drag the cursoron column boundaries to resize columns. You can also drag a column to a new position. ⚫ Tables are implemented by the JTable class, which extends JComponent. ⚫ One of its constructors is : JTable(Object data[ ][ ], Object colHeads[ ]) ⚫ Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional arraywith the column headings. ⚫ Hereare the steps for using a table in an applet: 1.Create a JTable object. 2. Create a JScrollPane object. (The arguments to the constructorspecify the table and the policies forvertical and horizontal scroll bars.) 3.Add the table to the scroll pane. 4. Add the scroll pane to the content pane of the applet.