0% found this document useful (0 votes)
28 views29 pages

PDF - JP-II UNIT 1 - 186 - N3

Uploaded by

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

PDF - JP-II UNIT 1 - 186 - N3

Uploaded by

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

CM4109

Unit 1. Abstract Windowing Toolkit (AWT)

1.1 Introduction to AWT, AWT classes, Window fundamentals, working with frame
Windows, creating a frame Window in an Applet, Creating windowed program.
1.2 Display information within a window.
1.3 Control Fundamentals, Labels, Using Buttons, Applying Check Boxes, Checkbox Group,
Choice Controls, Using Lists, managing scroll Bars, using a Text Field, Using a Text Area.
1.4 Understanding Layout Managers, Menu Bars and Menus, Dialog Boxes, File Dialog.
1.5 The delegation event model, Event classes, Sources of Events, Event Listener Interfaces.
1.6 Handling events by Extending AWT Components, Exploring the Controls, Menus, and
Layout manager.
1.7 Adapter classes, Inner classes
***************************************************************************

Introduction to AWT
• Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based
applications in java.
• AWT Package contains-
o A complete set of UI
o Support for UI containers
o An event system
• AWT is heavyweight i.e. its components use the resources of system.
• It contains numerous classes and methods that allows you to create and manage windows
and provides machine/platform independent interface for applications i.e. components are
displayed according to the view of operating system.
• AWT is one of the largest packagesi in Java.
• The java.awt package (import java.awt.*;) provides classes for AWT API such as
TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
• AWT is an object-oriented GUI framework.

GUI (Graphical User Interface)


• AWT is a library of classes which provides GUI tools to develop GUI applications and
applets.
• GUI offers user interaction via some graphical components like Window, frame, Panel,
Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc.
• Using these components, we can create an interactive user interface for an application.
• GUI provides result to end user in response to raised event.
• GUI is entirely based event.

1|Page 186_Shraddha Keshao Bonde_N3


CM4109

AWT class hierarchy

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

2|Page 186_Shraddha Keshao Bonde_N3


CM4109

• It defines over a hundred public methods that are responsible for managing events,
such as mouse and keyboard input, positioning and sizing the window, and repainting
etc.
• A Component object is responsible for remembering the current foreground and
background colours and the currently selected text font.
• Methods of Component Class:

2. Container
• The Container class is a subclass of the Component class that is used to define
components that have the capability to contain other components
• It provides methods for adding, retrieving, displaying, counting and removing the
components that it
contains.
• It provides the
deliverEvent() method for
forwarding events to its
components.
• The Container class also
provides methods for working with layouts.
• The layout classes control the layout of components within a container.
• A container is a type of component that provides a rectangular area within which other
components can be organized by LayoutManager.
• This makes for a multileveled containment system. A container is responsible for
laying out (that is, positioning) any components that it contains.

3. Window
• The Window class creates a top-level window, which sits directly on the desktop.
• Don’t create Window objects directly.
• The window is the container that have no borders and menu bars.
• Uses Frame, Dialog class which is subclass of Window class for creating window.

4. Panel
• Panel is a concrete subclass of Container.
• It doesn’t add any new methods which simply implements Container.
• Panel is the immediate superclass of Applet
• When screen output is directed to an applet, it is drawn on the surface of a Panel
object.

3|Page 186_Shraddha Keshao Bonde_N3


CM4109

• Panel is a window or one type of container that does not


contain a title bar, menu bar, or border.
• When you run an applet using an applet viewer, the applet
viewer provides the title and border.
• Uses add() to add component defined by container.
• Once these components have been added, you can position
and resize them manually using the setLocation( ), setSize(
), setPreferredSize( ), or setBounds( ) methods defined by
Component

5. Frame
• Frame encapsulates what is commonly thought of as a “window.”
• It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.
• If you create a Frame object from within an applet, it will contain a warning message,
such as “Java Applet Window,” to the user that an applet window has been created.
• This message warns users that the window they see was started by an applet and not
by software running on their computer.
• When a Frame window is created by a stand-alone application rather than an applet, a
normal window is created.

6. Dialog
• A dialog box is a temporary window an application creates to retrieve user input.

7. Canvas
• Although it is not part of the hierarchy for applet or frame windows, there is one other
type of window that you will find valuable: Canvas.
• The canvas component is a section of a window used primarily as a place to draw
graphics or display images i.e. Canvas encapsulates a blank window upon which you
can draw.
• Canvas is more similar to a container however Canvas component can’t be used as a
place to put components.
• Canvas class implements a GUI objects that supports drawing.
• It provides single parameter constructor and paint ( ) method.
Canvas c=new Canvas ();
c.resize (50, 50);
c.setBackground (Color.red);
add(c);

4|Page 186_Shraddha Keshao Bonde_N3


CM4109

AWT Classes

5|Page 186_Shraddha Keshao Bonde_N3


CM4109

Window Fundamentals
• A window provides a top level window on the screen ,with no borders or menu bar. Don’t
create Windows objects directly.
• The Window class provides an encapsulation of a generic window object
• The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level.
• The two most common windows are-
o those derived from Panel, which is used by applets, and
o those derived from Frame, which creates a standard application window.
• Much of the functionality of these windows is derived from their parent classes.
o Component,
o Container,
o Window,
o Frame,
o Panel
• Window is sub-classed by Frame and Dialog to provide capabilities needed to support
application main windows and Dialog box.
• Default Layout for window is Border Layout.
• A window is top level display area exists outside the browser or applet area you are
working on.
• It has no borders, window title, or menu bar that a
typical window manager might provide.
• Frame is a subclass that adds these parts (borders,
window title)
• Window class contains a single constructor that
creates a window that has a frame window as its
parent.
• The parent frame window is necessary because only objects of the Frame class or its
subclasses contain the functionality needed to support the implementation of an
independent window application.
• Window class implements important methods that are used by its Frame and Dialog
subclasses.

Working with frame Windows


• Frame is subclass of Window and has a title bar, menu bar, borders, and resizing corners.
• Frame object can be created from program or Applet.
• Through Applet: Warning message will display “Java Applet Window”.
• Through Program or Application: Normal window is created.
• Extends Frame class
• Constructor are:
o Frame()
o Frame(String title)
• Setting and Getting window size:

6|Page 186_Shraddha Keshao Bonde_N3


CM4109

o void setSize(int width, int height)


o void setSize(Dimension newsize)
o Dimension getSize()
• Showing and Hiding Frame
o void setVisible(boolean visibleFlag)
• Setting title to frame
o void setTitle(String title)
• Closing Frame: Four Ways
o Implements WindowListener interface.
o Extends WindowAdapter class.
o WindowAdapter Inner class.
o WindowAdapter anonymous inner classes.

Creating a frame Window in an Applet


• We can create stand-alone AWT based applications.
• A Frame provides main window for the GUI application.
• There are two ways to create a Frame :
o By instantiating Frame Class
o By extending Frame class
• Note- The setBounds(int x-axis, int y-axis, int width, int height)method is used in the
below example that sets the position of the awt button.

Difference between Component & Container class

Explain following methods with syntaxes:


1. setMenuBar() -
• This method is data member function of Frame class. This method used for to the
MenuBar of frame.
• This method accepts one argument as object of MenuBar class.
• The syntax of method as follows:

7|Page 186_Shraddha Keshao Bonde_N3


CM4109

public void setMenuBar (MenuBarmb)


• Example:
Frame frm=new Frame(“GPP”);
MenuBarmbr=new MenuBar();
frm.setMenuBar(mbr);

2. setFont()-
• This method is member method of Component class.
• To use a font that you have created, you must select it using setFont().
• The syntax of method as follows:
public void setFont(Font f)
• Here, “f” is the object that contains the desired font.Example:
Font font =new Font(“Times New Roman”,Font.BOLD,12);
setFont(font);

3. setBackground()-
• This method is data member function of Component class.
• To set the background color of window, use setBackground().
• The syntax of method as follows:
public void setBackground(Color newColor)
• Here, newColor specifies the new color.
• Example: setBackground(Color.red);

4. setVisible()-
• This method is data member function of Component class.
• These method is used for to make the component visible.
• The syntax of method as follows:
void setVisible(boolean visibleFlag)
• The component is visible if the argument to this method is true. Otherwise, it is
hidden.
• Example:
Frame f=new Frame()
f.setVisible(true)

Display information within a window


• In the most general sense, a window is a container for information.
• Although we have already output small amounts of text to a window in the preceding
examples, we have not begun to take advantage of a window ‘s ability to present high-
quality text and graphics.
• Indeed, much of the power of the AWT comes from its support for these items.
• We will see all upcoming program to see the power of AWT.

8|Page 186_Shraddha Keshao Bonde_N3


CM4109

AWT Control Fundamentals Points


Control Fundamentals
• Labels
• Using Buttons
• Applying Check Boxes
• Checkbox Group
• Choice Controls
• Using Lists
• Managing scroll Bars
• Using a Text Field
• Using a Text Area
These controls are subclasses of Component.
Controls are components that allows to interact
with the application

Label
• Labels are component that are used to display text in a container which can’t be edited by
user. This is a single line of text. Labels are read-only.
• They are generally used to guide the user to perform correct actions on the user interface,
also used for naming other components in the container.
• Syntax: Label l1=new Label (“name”);
add (l1);
• Label constructor:
1. Label (): creates an empty label, with its text aligned to left.
2. Label (String): creates label with given text, aligned left.
3. Label (String, int): creates a label with given text string and given alignment value. (0
is Label. LEFT, 1 is Label. RIGHT, 2 is Label. CENTER)
• Methods:
1. getText (): it returns a string containing this label’s text.
2. setText (String): it set a new text of label
3. GetAlignment ( ): it returns an integer value representing the alignment of label (0 is
Label. LEFT, 1 is Label. RIGHT, 2 is Label. CENTER)
4. SetAlignment (int): changes the alignment of this label to the given integer value (0, 1
or 2)

Button
• Button is a subclass of Component class and used to create buttons.
• The most widely used control is the push button.
• A push button is a component that contains a label and that generates an event when it is
pressed. Push buttons are objects of type Button.

9|Page 186_Shraddha Keshao Bonde_N3


CM4109

• Button defines these Constructors:


o Button( ) - to create a blank button.
o Button(String str) - to create button with specified text.
• It contains a label and that generates an event when it is pressed.
• Methods to perform operation: Setter and Getter Method.
o void setLabel(String str)
o String getLabel( )
• When Button pressed which generates an event when it is pressed.
• Implements ActionListener interface. Interface has defined actionPerformed() method,
called when event is generated.
• ActionEvent object is supplied as argument to the method.
• ActionEvent object refers both Button and Label of Button
• Label will get by using getActionCommand() from ActionEvent which passed.

Checkboxes
• 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.
• We change the state of a check box by clicking on it. Check boxes can be used
individually or as part of a group.
• Checkbox supports these constructors:
Checkbox() Checkbox(String str) Checkbox(String str,
boolean on)
• These methods are as follows:
• boolean getState( ) • String getLabel( )
• void setState(boolean on) • void setLabel(String str)
• The value of on determine initial state (true/false).
• Check box is selected or deselected, an item event is generated.
• For handling implements ItemListener interface
o ItemListener interface is defines itemStateChanged( ) method.
o ItemEvent object is supplied as the argument.
o getState() : Get Status about checkbox.
• Following methods determine and set status:
Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox
which)

Radio Buttons
• 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 often
called radio buttons.
• Check box groups are objects of type CheckboxGroup.
• Only the default constructor is defined, which creates an empty group.
• Constructor

10 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

o Checkbox(String str, boolean on, CheckboxGroup cbGroup)


o Checkbox(String str, CheckboxGroup cbGroup, boolean on)
• Methods
o Checkbox getSelectedCheckbox( )- It determines the group of checkbox.
o void setSelectedCheckbox(Checkbox which)-It sets the checkbox's group to the given
checkbox.

Choice Controls
• Used to create a pop-up list items.
• The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu.
• Each item in the list is a string that appears as a left justified label in the order it is added
to the Choice object.
• Default constructor –
o Choice()- It constructs a new choice menu/ create empty list.
• For add item in list and select active item:
o void add(String name)
o void select(int index)
o void select(String name)
o int getItemCount( )
• To determine selected item:
o String getSelectedItem( )
o int getSelectedIndex( )
o String getItem(intindex)

Lists
• 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. In
Choice only one item is shown.
• Constructors
List( ) List(int numRows) List(int numRows, boolean multipleSelect)
• Following methods are used to add items:
void add(String name) void add(String name, int index)
• For single selection items:
String getSelectedItem( ) int getSelectedIndex( )
• For Multi selection items:
String[ ] getSelectedItems( ) int[ ] getSelectedIndexes( )
• To retrieve item: String getItem(int index)
• To get Item Count: int getItemCount( )
• Active Item- void select(int index)
• Two types of event generated:
o For double clicked: ActionEvent generated.
o For select and deselect item: ItemEvent generated.

11 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• Implements ActionListener interface and ItemListener.

Scrollbars
• Scroll bars are used to select continuous values between a specified minimum and
maximum.
• Scroll bars may be oriented horizontally or vertically.
• It can be added to top-level container like Frame or a component like Panel.
• Constructors
1. Scrollbar( )
2. Scrollbar(int style)
3. Scrollbar(int style, int iValue, int tSize, int min, int max)
• The first form creates a vertical scroll bar.
• The second and third forms allow us to specify style Scrollbar.VERTICAL,
Scrollbar.HORIZONTAL.

Text field
• The TextField class implements a single-line text-entry area, 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 Constructors-
o TextField( )-- It constructs a new text field component
o TextField(int numChars)- It constructs a new textfield (empty) with given number of
columns
o TextField(String str)- It constructs a new text field initialized with the given string
text to be displayed
o TextField(String str, int numChars)- It constructs a new text field with the given text
and given number of columns (width)
• Following methods are for TextField:
o void setText(String str)
o String getText( )
o String getSelectedText( )
o Void setEditable(boolean canEdit)
o int setEchoChar(char ch )

Text Area
• Sometimes a single line of text input is not enough for a given task.
• To handle these situations, the AWT includes a simple multiline editor called TextArea.
TextArea is a subclass of TextComponent.
• Constructor-
o TextArea( )
o TextArea(int numLines, int numChars)

12 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

o TextArea(String str)
o TextArea(String str, int numLines, int numChars)
o TextArea(String str, int numLines, int numChars, int sBars)
• The values of sBar:
o SCROLLBARS_BOTH
o SCROLLBARS_NONE
o SCROLLBARS_HORIZONTAL_ONLY
o SCROLLBARS_VERTICAL_ONLY
• It supports: getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and
setEditable( )
• Other some methods:
o void append(String str)
o void insert(String str, int index)
o void replaceRange(String str, int startIndex, int endIndex)

Differentiate TextArea and TextField.

13 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

Differentiate Check Box and Radio Button.

Understanding Layout Managers


• Layout managers automatically positions components within a container, means the task
of lay outing can be done automatically by the Layout manager.
• A Layout Manager automatically arranges your controls within a window/ container by
using some type of algorithm.
• LayoutManager: Defines the interface for classes that know how to lay out Containers.
Layout Manager is set by setLayout( )
• Default Layout Manager
o Panel, Applet ---> Flow Layout
o Frame ---> Border Layout
• General Form- void setLayout(LayoutManager layObj)
• LayoutManager is an interface that is implemented by all the classes of layout managers.
• List of Layout Manger are as follows-
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. Grid Bag Layout

1. Flow Layout (default Layout)


• The Java FlowLayout class is used to arrange the components in a line, one after
another (in a flow).
• It is the default layout manager of the applet or panel.
• It places controls in the order in which they are added, linearly, fromleft to right and
from top to bottom in horizontal & vertical rows.

14 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• Components are normally centered in applet.


• FlowLayout implements a simple layout style, which is similar to how words flow in
a text editor.
• Components are laid out from the upper-left corner, left to right and top to bottom.
We can align components to left, right or center.
• 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.
• To create flow Layout :
o FlowLayout f1=new FlowLayout ();
o FlowLayout f2=new FlowLayout (FlowLayout.LEFT); // FlowLayout(int how)
o FlowLayout f3=new FlowLayout(FlowLayout.LEFT,10,30);
o setLayout(f1) // FlowLayout( int how, int horz, int vert)
• FlowLayout Methods:
o int getAlignment()
o int getHgap()
o int getVgap()
o int setAlignment(int align)
o int setHgap(int hgap)
o int setVgap(int vgap)

2. Border Layout
• The BorderLayout class implements a common layout style for top-level windows.
• Border layout is the default layout manager for all window, dialog and frame class.
• In Border layout, components are added to the edges of the container, the center area
is allotted all the space that’s left over.
• 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.
• When you add a component to the layout you must specify which area to place it in.
• Here are the constructors defined by BorderLayout:
o BorderLayout( ) - creates a default border layout.
o BorderLayout(int horz, int vert)- allows you to specify the horizontal and vertical
space left between components in horz & vert.
• BorderLayout defines the following constants that specify the regions:
o BorderLayout.CENTER
o BorderLayout.SOUTH
o BorderLayout.EAST
o BorderLayout.WEST
o BorderLayout.NORTH
• When adding components, you will use these constants with the following form of
add( ) which idefined by Container:
void add(Component compObj, Object region);

15 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• Here, compObj is the component to be added, and region specifies where the
component will be added.

3. Grid Layout
• The Java GridLayout class is used to arrange the components in a rectangular grid.
One component is displayed in each rectangle.
• GridLayout lays out components in a two-dimensional grid.
• The Grid layout class puts each component into a place on a grid that is equal in size
to all the other places.
• The grid is given specific dimensions when created; Components are added to the grid
in order, starting with upper-left corner to right
• Components are given equal amounts of space in the container.
• Grid layout is widely used for arranging components in rows and columns, when we
instantiate a GridLayout.
• However unlike, Flow Layout, here underlying components are resized to fill the row-
column area. if possible.
• Grid Layout can reposition objects after adding / removing components.
• Whenever area is resized, components are also resized.
o GridLayout( )
o GridLayout b1=new GridLayout (2, 3);
o SetLayout (b1)
o GridLayout(int numRows, int numColumns, int horz, int vert)

4. Card Layout
• The CardLayout is a bit on the strange side.
• The CardLayout class is unique among the other layout manager 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.
• A CardLayout usually manages several components, displaying one of them at a time
and hiding the rest. All the components are given the same size.
• Usually, the CardLayout manages a group of Panels (or some other container), and
each Panel contains several components of its own.
• With a little work, you can use the CardLayout to create tabbed dialog boxes or
property sheets, which are not currently part of AWT.
• CardLayout lets you assign names to the components it is managing and lets you jump
to a component by name. You can also cycle through components in order.
• Note: The CardLayout class manages two or more components that share the same
display space. Conceptually, each component is like a playing card in a stack, where
only the top card is visible at any time.
• The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
• CardLayout provides these two constructors:
o CardLayout( )- Creates a card layout with zero horizontal & vertical gap.

16 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

o CardLayout(int horz, int vert)- Creates a card layout with the given horizontal and
vertical gap.
• Methods:
o public void first(Container parent)
o public void next(Container parent)
o public void previous(Container parent)
o public void last(Container parent)
o public void show(Container parent, String name)

5. GridBag Layout
• GridBagLayout is the most complex and flexible of the standard layout.
• Each GridBagLayout object maintains a dynamic rectangular grid of cells, with each
component occupying one or more cells, called its display area.
• Each component managed by a gridbag layout is associated with an instance of
GridBagConstraints class that specifies how the component is laid out within its display
area.
• With the GridBagLayout, you can organize components in multiple rows and columns,
stretch specific rows or columns when space is available, and anchor objects in different
corners.
• GridBagLayout arranges components in a horizontal and vertical manner.
• GridBagLayout, elements can have different sizes and can occupy multiple rows or
columns. The rows in the grid can have different heights, and grid columns can have
different widths.
• Constructors:
new GridBagLayout();
• To customize a GridBagConstraints object by setting one or more of its instance
variables:

17 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

Menu Bars and Menus


• Top-level window can have a 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.
• Classes: MenuBar Class Defines only default constructor.
o MenuBar : Contains one or more Menu objects
o Menu : Contains one or more MenuItem objects or list
o MenuItem : Object something that selected by user.
• It is also possible to include checkable menu items.

MenuBar
• The MenuBar class provides menu bar bound to a frame.
• MenuBar class extends MenuComponent class and implements MenuContainer,
Accessible interface.
• Constructor - MenuBar(): Creates a new menu bar.
• Method-
o Menu add(Menu m): Adds the specified menu to the menu bar.
o Menu getMenu(int i): Gets the specified menu.

Menu
• A menu has a pull-down list of menu items from which the user can select one at a time.
• When many options in multiple categories exist for selection by the user, menus are the
best choice since they take less space on the frame.
• Menu class extends MenuItem class and implements MenuContainer, Accessible
interface.

Menu Hierarchy-
• Menu creation involves many classes, like MenuBar, MenuItemand Menu and one is
added to the other.
• A MenuBar is capable of holding the menus and a Menu can hold menu items.
• Menus are placed on a menu bar.

Procedure for Creating Menus


• Create menu bar
• Add menu bar to the frame
• Create menus

18 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• Add menus to menu bar


• Create menu items
• Add menu items to menus
• Event handling

Menu Class Constructors


• Menu( )
• Menu(String optionName)
• Menu(String optionName, boolean removable)
• Here, optionName specifies the name of the menu selection.

Individual menu items constructors:


• MenuItem( )
• MenuItem(String itemName)
• MenuItem(String itemName, MenuShortcut keyAccel)

Methods
Disable or enable a menu item by using:
• void setEnabled(boolean enabledFlag)
• boolean isEnabled( )
Label set and get using:
• void setLabel(String newName)
• String getLabel( )
Checkable menu item by using a subclass of MenuItem called CheckboxMenuItem. :
• CheckboxMenuItem( )
• CheckboxMenuItem(String itemName)
• CheckboxMenuItem(String itemName, boolean on)
Status about checkable MenuItem:
• boolean getState( )
• void setState(boolean checked)
For add MenuItem:
• MenuItem add(MenuItem item)
For add MenuBar
• Menu add(Menu menu)
To get Item from Menu:
• Object getItem( )

19 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

Dialog Boxes Control


• The dialog box to hold a set of related controls.
• Dialog boxes are primarily used to obtain user input.
• They are similar to frame windows, except that dialog boxes are always child windows of
a top-level window.
• Dialog boxes don’t have menu bars.
• In other respects, dialog boxes function like frame windows. (You can add controls to
them, for example, in the same way that you add controls to a frame window.)
• Dialog boxes may be modal or modeless.
• When a modal dialog box is active, all input is directed to it until it is closed. This means
that you cannot access other parts of your program until you have closed the dialog box.
• When a modeless dialog box is active, input focus can be directed to another window in
your program. Thus, other parts of your program remain active and accessible.
• Two commonly used constructors are shown here:
o Dialog (Frame parentWindow, boolean mode)
o Dialog (Frame parentWindow, String title, boolean mode)
o Here, parentWindowis the owner of the dialog box.
• If mode is true, the dialog box is modal. Otherwise, it is modeless.
• The title of the dialog box can be passed in title.
• Generally, you will subclass Dialog, adding the functionality required by your
application.
• Notice that when the dialog box is closed, dispose( ) is called. This method is defined by
Window, and it frees all system resources associated with the dialog box window.
• Steps to create Dialog Box:
o Create Frame or Applet
o Create another class which extends Dialog class.
o Call this new class from Frame/Applet class.
o In constructor of Extended Dialog class, use super method and pass values to
constructor of Dialog

File Dialog
• Java provides a built-in dialog box that lets the user specify a file.
• To create a file dialog box, instantiate an object of type FileDialog.
• This causes a file dialog box to be displayed. Usually, this is the standard file dialog box
provided by the operating system.
• Constructor:
o FileDialog(Frame parent)
o FileDialog(Frame parent, String boxName)
o FileDialog(Frame parent, String boxName, int how)
• If how is FileDialog.LOAD, then the box is selecting a file for reading. If how is
FileDialog.SAVE,the box is selecting a file for writing. If how is omitted, the box is
selecting a file for reading.

20 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• FileDialog provides methods that allow you to determine the name of the file and its path
as selected by the user.
• Methods: These methods return the directory and the filename.
o String getDirectory( )
o String getFile( )

The delegation event model Points


• The delegation event model
• Event classes
• Sources of Events
• Event Listener Interfaces.

The delegation event model / Event handling


• The delegation event model derives its name from the fact that event handling is
delegated from an event source to one or more event listeners interfaces defined by
java.awt.event.
• Changing the state of an object is known
as an Event. Example: Pressing or
clicking the button, entering a character
in Textbox.
• Any GUI program is Event Driven. In
Event-Driven programming a piece of
event handling codes can execute when
an event has been fired in reference to
the user input.
• Events are supported by a number of
Java Packages like: java util, java.awt
and java.awt.event.
• Delegation Event Model is based on the concept of an "Event Source" and "Event
Listeners".

How Events are handled


• There are main three components are required to handle Event.
• Event Source: It is objects that can generates an event (message) and send it to one or
more listeners registered with the Source.
• Events: An Event is any change of state of an object.
• Event Listeners: It is an object that the listener to the event. Once the event (message) is
received by the Event Listener can the process of event and then returns it.
• When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument.
• The Event listener represents the interfaces responsible to handle events.

21 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• Every method of an event listener method has a single argument as an object which is
subclass of EventObject class.

Event classes
• Event Model defines a large number of event classes. At the root of the Java event class
hierarchy is java.util.EventObject.
• Every event is a subclass of java.util.EventObject.
• It is a very general class with only one method of interest.
• Object getSource()-This method returns the object that originated the event. Every event
has a source object, from which the event originated. This method returns a reference to
that source.
• java.awt.AWTEvent: AWT events, which is the main concern here, are subclasses of
java.awt.AWTEvent. This is the super class of all the delegation model event classes. The
most interesting method in this class is:
• int getID()-This method returns the ID of the event. An event's ID is an int that specifies
the exact nature of the event. This value is used to distinguish the various types that are
represented by any event class.

Event classes Table

Event Listener Interfaces


• A listener is an object that is notified when an event occurs.
• It has two major requirements-
o First, it must have been registered with one or more sources to receive notifications
about specific types of events.
o Second, 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.

22 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

• Any object may receive and process one or both of these events if it provides an
implementation of this interface.
• The class which processes the ActionEvent should implement this interface. The object of
that class must be registered with a component.
• The object can be registered using the addActionListener() method.
• When the action event occurs, that object's actionPerformed() method is invoked
• Interface declaration of java.awt.Event.ActionListener
o public interface ActionListener extends EventListener
• Interface methods: void actionPerformed (ActionEvent e)
• List of component and there required listener interface

23 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

Describe MouseEvent & MouseListener interface with example


MouseEvent
• A MouseEvent is fired to all its registered listeners.
• When you press, Release or click a mouse button at the source object or
position of the mouse pointer at (Enter) and away (Exit) from the source object.
• Methods of MouseEvent class: -

24 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

MouseListener
• A MouseListener interface is associated with MouseEvent class it can defines the
Methods to handle MouseEvents.
• Methods of MouseListener:

Describe KeyEvent & KeyListener interface with example


KeyEvent
• The KeyEvent is generated when a key is typed, pressed or released.
• In order to handle the KeyEvent, we need to register KeyListener
• Methods of KeyEvent class: -

KeyListener
• The KeyListener interface is associated with KeyEvent class.
• It defines three methods to handle KeyEvents.
• Methods of KeyListener:

25 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

AWT WindowEvent class


• The WindowEvent is generated when a window is opened, closed, activated, deactivated,
Iconified, deIconified.
• In order to handle the WindowEvent, we need to register windowListener.
• The WindowListener interface is associated with WindowEvent class.
• It defines Eevent methods to handle WindowEvents.
• Methods of WindowListener: -

Sources of Events - adding


• 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.
• Here is the general form: public void addTypeListener(TypeListener el)
• Here, Type is the name of the event and el is a reference to the event listener.
• For example, the method that registers a keyboard event listener is called
addKeyListener( ). The method that registers a mouse motion listener is called
addMouseMotionListener( ).
• 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, notifications are sent only to listeners that register to receive them.

Sources of Events - removing


• When such an event occurs, the registered listener is notified. This is known as unicasting
the event.
• A source must also provide a method that allows a listener to un-register an interest in a
specific type of event.
• The general form of such a method is this:
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, we would call removeKeyListener( ).

26 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

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

Handling events by Extending AWT Components


• The delegation event model was introduced in Event handling, and all of the programs in
this book so far have used that design.
• Java also allows you to handle events by subclassing AWT components.
• Doing so allows you to handle events in much the same way as they were handled under
the original 1.0 version of Java.
• Of course, this technique is discouraged, because it has the same disadvantages of the
Java 1.0 event model, the main one being inefficiency.
• To extend an AWT component, you must call the enableEvents( ) method of Component.
Its general form is shown here: protected final void enableEvents(long eventMask)
• Several are shown here:

• You must also override the appropriate method from one of your superclasses in order to
process the event.
• Following Table lists the methods most commonly used and the classes that provide them.

• The following sections provide simple programs that show how to extend several AWT
components.

27 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

Adapter classes
• Java adapter classes provide the default implementation of listener interfaces. The adapter
classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
• If you inherit the adapter class, you will not be forced to provide the implementation of
all the methods of listener interfaces. So it saves code.
• Event adapters facilitate implementing listener interfaces.
• Many event listener interfaces have more than one event listener methods. For such
interfaces, Java technology defines adapter classes.
• These have empty implementation (stubs) of all the event listener methods defined in the
interface they implement.
• A listener can subclass the adapter and override only stub methods for handling events of
interest.
• Pros/Advanrtages of using Adapter classes:
o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
• Java provides a special feature, called an adapter class, that can simplify the creation of
event handlers in certain situations.
• An Event Adapter class are Abstract classes and gives a default implementation of all the
methods in an EventListener interface.
• 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.
• Few Event Adapter classes are FocusAdapter, KeyAdapter, MouseAdapter,
WindowAdapter and MouseMotionAdapter etc.
• For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ) .
• The table below lists the low level event listener interfaces and their adapters.

Inner classes
• Local inner classes are often used in Java to define callbacks for GUI code.
• Inner classes work well even if your event handler needs access to private instance
variables from the enclosing class. As long as you don't declare an inner class to be static,

28 | P a g e 186_Shraddha Keshao Bonde_N3


CM4109

an inner class can refer to instance variables and methods just as if its code is in the
containing class.
• Components can then share an object that implements an event handling interface or
extends an abstract adapter class, containing the code to be executed when a given event
is triggered.
• Anonymous Inner Classes-
• We can also create Anonymous inner classes (i.e., inner classes that have no name) to
shorten the process of declaring an inner class and creating an instance of that class into
one step.
• There are some restrictions on creating anonymous inner classes as below-
o Must always extend a superclass or implement an interface
o Must implement all the abstract methods in the superclass or in the interface
o Always uses the no-arg constructor from its superclass to create an instance
o Is compiled into a class named OuterClassName$inner.class
o So for example, if the outer class Test has two anonymous inner classes, these two
classes are compiled into Test$1.class and Test$2.class
• For understanding the benefit provided by inner classes, consider the applet shown in the
following Example. It does not use an inner class.
• Its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or
browser when the mouse is pressed.
• There are two top-level classes in this program.
o InnerClassDemo extends Applet, and
o MyMouseAdapter extends MouseAdapter.
• The init( ) method of InnerClassDemo instantiates MyMouseAdapter and provides this
object as an argument to the addMouseListener( ) method.
• Notice that a reference to the applet is supplied as an argument to the MyMouseAdapter
constructor. This reference is stored in an instance variable for later use by the
mousePressed( ) method.
• When the mouse is pressed, it invokes the showStatus( ) method of the applet through the
stored applet reference. In other words, showStatus( ) is invoked relative to the applet
reference stored by MyMouseAdapter.
***************************************************************************

29 | P a g e 186_Shraddha Keshao Bonde_N3

You might also like