PDF - JP-II UNIT 1 - 186 - N3
PDF - JP-II UNIT 1 - 186 - N3
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.
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.
• 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.
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);
AWT Classes
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.
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)
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.
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
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.
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)
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)
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);
• 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.
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:
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.
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( )
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.
• 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( )
• 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.
• 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
MouseListener
• A MouseListener interface is associated with MouseEvent class it can defines the
Methods to handle MouseEvents.
• Methods of MouseListener:
KeyListener
• The KeyListener interface is associated with KeyEvent class.
• It defines three methods to handle KeyEvents.
• Methods of KeyListener:
• 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.
• 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.
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,
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.
***************************************************************************