Anda di halaman 1dari 30

Unit-4

Event: Changing the state of an object is known as an event.


Example: click on button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
Event source: event source is a code which will generate an event
AWT components, we came to know every component (except Panel and Label) generates events
when interacted by the user like clicking over a button or pressing enter key in a text field etc.
Listeners handle the events. Let us know the style (or design pattern) Java follows to handle the
events.

Prepared By: Y.Amaraiah


Event Handling in Java

The GUI in Java processes the interactions with user via mouse; keyboard and various user controls
such buttons, checkbox, text-field etc. as the events. These events are to be handled properly to
implement Java Programming as an Event-Driven Programming.

FIG: Event-Driven Programming

Delegation Event Model


 Modern approach to handle event which defines standard and consistent mechanisms to generate
and process events
 Concept in Delegation Model:
 A source generates an event and sends it to one or more listeners
 Listener waits until it receives an event
 When Listener receives an event , it processes and then returns
 Major advantage of this model is that the event handling model code can be separately
maintained from those which generate the event.
 In this model each listener should be assigned to the source in order to receive an event
notification

Prepared By: Y.Amaraiah


 So another advantage that can be realized is that the events can be sent only to those listeners
that are required to receive them
 In traditional event handling mechanism, an event was propagated up the containment hierarchy
until it was handled by a component which required the components to receive events that they
did not process and wasted the valuable time.

Components in Event Handling


 Events
 Event Sources
 Event Listeners/ Handlers

Events
 Defined as an object that describes a change in state of a source object
 Java defines a number of such Event Classes inside java.awt.event package
Event Classes Description
ActionEvent Generated when a button is clicked, List item is double clicked, Menu Items is
selected
AdjustmentEvent Generated when a Scroll Bar is manipulated
ComponentEvent Generated when a Java Components is hidden,moved, resized, or becomes
visible
ContainerEvent Generated when a component is added to or removed from Containers
FocusEvent Generated when a component gains or looses keyboard focus
InputEvent Abtract super class for all components input event classes such as KeyEvent
and MouseEvent
ItemEvent Generated when a checkbox or item list is clicked and 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, released;
also occurs when mouse enters or exits a component
MouseWheelEvent Generated when the mouse wheel is moved
TextEvent Generated when a values of text component change
WndowEvent Generated whena window is activated, closed, deactivated, deiconified,
iconified, opened or quit

Event Source
 A source is an object that generates an event
 Event generation occurs when internal state of that object changes in some way
 A source must register listeners in order for the listeners to receive the notifications about a
specific type of events

Prepared By: Y.Amaraiah


 General form of adding such listeners:
o public void addTypeListener(TypeListener obj)
o Eg:
Button btnObj=new Button("Enter");
btnObj.addActionListener(el);
//el is the object of class that implements ActionListener interface

Event Source Description


Button Generates ActionEvent when button is pressed
Checkbox Generates ItemEvent when the checkbox is selected or deselected
Choice Generates ItemEvent when the choice is changed
List Generates ActionEvent when an item is double-clicked; generates
ItemEvent when an item is selected or deselected
Menu Item Generates ActionEvent when a menu item is selected and when a
checkable menu item is selected or deselected
Scroll bar Generates AdjustmentEcent when the scroll bar is manipulated
Text Component Generates TextEvent when the user enter a character
Window Generates WindowEvent when a window is activated, closed,
deactivated, deiconified, iconified, opened or quit

Event Listeners
 A listener is an object that is notified when an event occurs
 It has two major requirements:
o It should be registered to one more source object to receive event notification
o It must implement methods to receive and process those notifications
 Java has defined a set of interfaces for receiving and processing the events under the
java.awt.event package

Event Listener Description Methods Provided


Interface (Default void return type for all
methods)
ActionListener Defines one method to actionPerformed(ActionEvent ae)
receive ActionEvent
AdjustmentListener Defines one method to adjustmentValueChanged (AdjustementEvent
receive AdjustementEvent ae)
ComponentListener Defines four methods to componentResized(ComponentEvent ce)
recognize when a componentMoved(ComponentEvent ce)

Prepared By: Y.Amaraiah


component is hidden, componentShown(ComponentEvent ce)
moved, resized, or shown componentHidden(ComponentEvent ce)
ContainerListener Defines two methods to componentAdded(ContainerEvent ce)
recognize when a componentRemoved(ContainerEvent ce)
component is added to or
removed from a container
FocusListener Defines two methods to focusGained(FocusEvent fe)
recognize when a focusLost(FocusEvent fe)
component gains or loses
keyboard focus
ItemListener Defines one method to itemStateChanged(ItemEvent ie)
recognize when the state of
an item changes
KeyListener Defines three methods to keyPressed(KeyEvent ke)
recognize when a key is keyReleased(KeyEvent ke)
pressed, released or typed keyTyped(KeyEvent ke)

MouseListener Defines five methods to mouseClicked(MouseEvent me)


recognize when mouse is mouseEntered(MouseEvent me)
clicked, enters a mouseExited(MouseEvent me)
component, exits a mousePressed(MouseEvent me)
component, is pressed or is mouseReleased(MouseEvent me)
released
MouseMotionListener Defines two methods to mouseDragged(MouseEvent me)
recognize when the mouse mouseMoved(MouseEvent me)
is dragged or moved.
MouseWheelListener Defines one method to mouseWheelMoved(MouseWheenEvent me)
recognize when the mouse
wheel is moved
TextListener Defines one method to textChanged(TextEvent te)
recognize when a text value
changes
WindowFocusListener Defines two methods to windowGainedFocus(WindowEvent we)
recognize when a window windowLostFocus(WindowEvent we)
gains or loses input focus
WindowListener Defines seven methods to windowActivated(WindowEvent we)
recognize when a window is windowClosed(WindowEvent we)
activated, closed, windowClosing(WindowEvent we)
deactivated, deiconified,, windowDeactivated(WindowEvent we)

Prepared By: Y.Amaraiah


iconified, opened or quit windowDeiconified(WindowEvent we)
windowIconified(WindowEvent we)
windowOpened(WindowEvent we)

Event Handling Mechanisms in Java


 Using Delegation Event Model
 Using Adapter Classes
 Using Inner Classes
 Using Anonymous Inner Classes

Using Delegation Event Model


 Steps followed in Delegation Event Model for event handling in Java:
1. Implement the appropriate interface in the listener so that it will receive the type of event
desired
2. Implement code to register the listener as a recipient for the event notifications
 Example Code:

Prepared By: Y.Amaraiah


//Demonstration of Delegation Event Model for Event Handling In Java
//DelegationEventModel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyActionHandler implements ActionListener //Creating a Action Listener of our own


{
DelegationEventModel myFrame;

MyActionHandler(DelegationEventModel frme)
{
myFrame=frme;
}

public void actionPerformed(ActionEvent ae)


// Implementing the method of ActionListener Interface
{
myFrame.tObj.setText("You Just Pressed The Button");
myFrame.btnObj.setVisible(false);
}
}
class DelegationEventModel extends Frame implements KeyListener
// Implementing Key Listener within Frame itself
{
Button btnObj;
Panel pnlObj;
TextField tObj;
MyActionHandler myAction;

DelegationEventModel(String str)
{
super(str);
myAction=new MyActionHandler(this); //creating object of MyActionHandler
setLayout(new FlowLayout());

Prepared By: Y.Amaraiah


btnObj=new Button("OKAY");
pnlObj=new Panel();
pnlObj.setLayout(new FlowLayout());
tObj=new TextField("Check This Out",50);

tObj.setEnabled(false);

pnlObj.add(btnObj);
pnlObj.add(tObj);

btnObj.addActionListener(myAction); //Registering Action Listener for the Button

add(pnlObj);
addKeyListener(this); //Register itslef as the key Listener for the Frame
setVisible(true);
setSize(500,200);
}
public void keyTyped(KeyEvent ke)
// Implementing the method of KeyListener Interface
{
JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());
btnObj.setVisible(true);
}
public void keyReleased(KeyEvent ke)
// Implementing the method of KeyListener Interface
{
//setTitle("Key Up");
}
public void keyPressed(KeyEvent ke)
// Implementing the method of KeyListener Interface
{
//setTitle("Key Down");
}

Prepared By: Y.Amaraiah


public static void main(String[] args)
{
DelegationEventModel objMain=new DelegationEventModel("Delegation Event Model
for Event Handling");
}
}

Using Adapter Classes


 In the above example, while implementing an interface for listener there is a overhead of
implementing all the methods provided by the interface even if we don’t want to
 For EG: when we implement KeyListener interface then we should give the implementation code
for all three methods provided by this interface as in above example
 At times we might not need to implement all methods of those interface class, and this is done in
Java by the special feature named Adapter classes
 Adapter Classes are the classes which provided the empty implementation of an the event
listener interface that it is associated with
 For an instance KeyAdapter is an adapter class for keyListener interface and the structure of that
KeyAdapter class looks like:
class KeyAdapter implements KeyListener
{
void keyTyped(KeyEvent ke)
{
}
void keyReleased(KeyEvent ke)
{
}
void keyPressed(KeyEvent ke)
{
}
}
 Now if we extend KeyAdapter Class instead of implementing KeyListener Interface, then only
required methods can be overridden
 For Eg:

Prepared By: Y.Amaraiah


class MyActionHandler extends KeyAdapter
{
void keyTyped(KeyEvent ke)
{
//required codes
}
}
class MainClass extends Frame
{
MainClass()
{
super("My Frame");
MyActionHandler myAction=new MyActionHandler();
addKeyListener(myAction);
}
public static void main(String[] args)
{
//Main function codes
}
}
Program Demo Example for Using Adapter Class
//Demonstration of Adapter Classes for Event Handling In Java
//UsingAdapter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyActionHandler extends KeyAdapter


//Creating a Action Listener of our own using Adapter Class
{
UsingAdapter myFrame;
MyActionHandler(UsingAdapter frme)
{
myFrame=frme;
}

Prepared By: Y.Amaraiah


public void keyTyped(KeyEvent ke)
// Overriding the required method only of KeyAdapter Class
{
JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());
myFrame.btnObj.setVisible(true);
}

}
class UsingAdapter extends Frame implements ActionListener
// Implementing Action Listener within Frame itself
{
Button btnObj;
Panel pnlObj;
TextField tObj;
MyActionHandler myAction;

UsingAdapter(String str)
{
super(str);
myAction=new MyActionHandler(this); //creating object of MyActionHandler
setLayout(new FlowLayout());
btnObj=new Button("OKAY");
pnlObj=new Panel();
pnlObj.setLayout(new FlowLayout());
tObj=new TextField("Check This Out",50);
tObj.setEnabled(false);
pnlObj.add(btnObj);
pnlObj.add(tObj);
btnObj.addActionListener(this); //Registering Action Listener for the Button
add(pnlObj);
addKeyListener(myAction); //Register itslef as the key Listener for the Frame
setVisible(true);
setSize(500,200);
}

Prepared By: Y.Amaraiah


public void actionPerformed(ActionEvent ae)
// Implementing the method of ActionListener Interface
{
tObj.setText("You Just Pressed The Button");
btnObj.setVisible(false);
}
public static void main(String[] args)
{
UsingAdapter objMain=new UsingAdapter("Adapter Class for Event Handling");
}
}

Commonly Used Listener Interfaces Implemented By The Adapter Classes


Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

Using Inner Classes for Event Handling


 Class defined within other class or even within an expression is inner class
 Event handling in this method is carried out by an inner listener class defined within the class
with the GUI Components
 Example Code:

//Demonstration of Adapter Classes for Event Handling In Java


//UsingInner.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class UsingInner extends Frame implements ActionListener


// Implementing Action Listener within Frame itself

Prepared By: Y.Amaraiah


{
Button btnObj;
Panel pnlObj;
TextField tObj;
MyActionHandler myAction;
UsingInner(String str)
{
super(str);
myAction=new MyActionHandler(this); //creating object of MyActionHandler
setLayout(new FlowLayout());
btnObj=new Button("OKAY");
pnlObj=new Panel();
pnlObj.setLayout(new FlowLayout());
tObj=new TextField("Check This Out",50);
tObj.setEnabled(false);
pnlObj.add(btnObj);
pnlObj.add(tObj);
btnObj.addActionListener(this); //Registering Action Listener for the Button
add(pnlObj);
addKeyListener(myAction); //Register itslef as the key Listener for the Frame
setVisible(true);
setSize(500,200);
}
public void actionPerformed(ActionEvent ae)
// Implementing the method of ActionListener Interface
{
tObj.setText("You Just Pressed The Button");
btnObj.setVisible(false);
}
public static void main(String[] args)
{
UsingInner objMain=new UsingInner("Inner Class for Event Handling");
}
class MyActionHandler extends KeyAdapter
//Creating an Inner Action Listener of our own using Adapter Class

Prepared By: Y.Amaraiah


{
UsingInner myFrame;
MyActionHandler(UsingInner frme)
{
myFrame=frme;
}
public void keyTyped(KeyEvent ke)
// Overriding the required method only of KeyAdapter Class
{
JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());
myFrame.btnObj.setVisible(true);
}

}
}

Using Anonymous Inner Classes


 An anonymous inner class is one that is not assigned a name and is defined inside an expression
 For event handling anonymous listener classes are defined while registering listener to the source
 For Eg:
Button myBtn =new Button("Sample");
myBtn.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//tasks to do
}
});
 General Structure is as:
eventSource.addTypeListener(new TypeListener()
{
//implement the methods within TypeListener Interface
});

Prepared By: Y.Amaraiah


Example Code
//Demonstration of Adapter Classes for Event Handling In Java
//UsingAnonymous.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class UsingAnonymous extends Frame


{
Button btnObj;
Panel pnlObj;
TextField tObj;
MyActionHandler myAction;
UsingAnonymous(String str)
{
super(str);
myAction=new MyActionHandler(this); //creating object of MyActionHandler
setLayout(new FlowLayout());
btnObj=new Button("OKAY");
pnlObj=new Panel();
pnlObj.setLayout(new FlowLayout());
tObj=new TextField("Check This Out",50);
tObj.setEnabled(false);
pnlObj.add(btnObj);
pnlObj.add(tObj);

btnObj.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
// Implementing the method of ActionListener Interface
{
tObj.setText("You Just Pressed The Button");
btnObj.setVisible(false);
}
}); //Registering and implementing Anonymous Action Listener for the Button

Prepared By: Y.Amaraiah


add(pnlObj);
addKeyListener(myAction); //Register itslef as the key Listener for the Frame
setVisible(true);
setSize(500,200);
}
public static void main(String[] args)
{
UsingAnonymous objMain=new UsingAnonymous("Anonymous Inner Class for Event
Handling");
}
class MyActionHandler extends KeyAdapter
//Creating an Inner Action Listener of our own using Adapter Class
{
UsingAnonymous myFrame;
MyActionHandler(UsingAnonymous frme)
{
myFrame=frme;
}
public void keyTyped(KeyEvent ke)
// Overriding the required method only of KeyAdapter Class
{
JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());
myFrame.btnObj.setVisible(true);
}

}
}
mouse event handling in java

The KeyEvent Class:


There are three types of key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED. The first two events are generated when a key is pressed or
released. The last event occurs when a character is generated.
Many other integer constants that are defined by KeyEvent:

Prepared By: Y.Amaraiah


nt is a subclass of InputEvent and uses the constructor:
KeyEvent (Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type. The system time at which the key is pressed is passed in when. The modifier argument
specifies which modifiers were pressed when this key event occurred. The virtual key code is passed
in code. The character equivalent is passed in ch. If no valid character exist, then ch contains
CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.
The getKeyChar() method returns the character that was entered and getKeyCode() method returns
the key code.
char getKeyChar ()
int getKeyCode ()
The MouseEvent Class:
There are eigth types of mouse events. MouseEvent class defines the following integer constants:

MouseEvent class is a subclass of InputEvent. It uses the constructor:


MouseEvent (Component src, int type, long when, int modifier, int x,int y, int clicks, boolean
triggersPopup)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type. The system time at which the mouse event occurred is passed in when. The modifier argument
specifies which modifiers were pressed when this mouse event occurred. The coordinates of the
mouse are passed in x and y. The click count is passed in clicks.The triggerPopup flag indicates if this
event causes a popup menu to appear on this platform.
The getX() and getY() methods returns the x and y coordinates of the mouse within the component
when the event occurred.
int getX()
int getY()
Another method getPoint() method is used to obtain the coordinates of the mouse:
Point getPoint()
The translatePoint() method changes the location of the event.
void translatePoint (int x, int y)
Here, the arguments x and y are added to the coordinates of the event.
The getClickCount() method returns the number of mouse clicks for an event:
int getClickCount ()
The isPopupTrigger() method tests if this event causes a pop-up menu to appear on this platform.

Prepared By: Y.Amaraiah


boolean isPopupTrigger()
The getButton() method that represent the button that caused the event:
int getButton()

NOBUTTON indicates that no button was pressed or released.


The MouseWheelEvent Class:
MouseWheelEvent is a subclass of MouseEvent. Mouse wheels are used for scrolling.
MouseWheelEvent defines two integer constants:

MouseWheelEvent uses the constructor:


MouseWheelEvent (Component src, int type, long when, int modifier, int x,int y, int clicks, boolean
triggersPopup, int scrollHow, int amont, int count)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type. The system time at which the mouse event occurred is passed in when. The modifier argument
specifies which modifiers were pressed when this mouse event occurred. The coordinates of the
mouse are passed in x and y. The number of clicks the wheel has rotated is passed in clicks. The
triggerPopup flag indicates if this event causes a popup menu to appear on this platform. The
scrollHow value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL. The number of
units to scroll is passed in amount. The count parameter indicates the number of rotational units
that the wheel moved.
The getWheelEvent() method returns number of rotational units:
int getWheelRotation()
A positive value is returned if the wheel moved counterclockwise. The negative value is returned if
the wheel moved clockwise.
The getScrollType() method returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
int getScrollType ()
If WHEEL_UNIT_SCROLL is returned getScrollAmount() can be called to obtain the number of units
scrolled:
int getScrollAmount()
The TextEvent Class:
TextEvents are defines the integer constant TEXT_VALUE_CHANGED.
TextEvent has the constructor:
TextEvent (Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type.
The text event object does not include the characters currently in the text components that generated
the event.
The Window Event Class:
Window Event class defines the following integer constants that can be used to identify them:

Prepared By: Y.Amaraiah


WindowEvent class is a subclass of ComponentEvent. It uses the constructor:
WindowEvent (Window src, int type)
WindowEvent (Window src, int type, Window other)
WindowEvent (Window src, int type, int fromState, int toState)
WindowEvent (Window src, int type, Window other, int fromState, int toState)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type. other specifies the opposite window when a focus or activation event occurs. The fromState
specifies the prior state of the window, and the toState specifies the next state of the window.
The getWindow() method returns the object that generated the event.
Window getWindow()
WindowEvent also defines methods that returns the opposite window (When a focus or activation
event has occurred), the previous window state and the current window state:
Window getOppositeWindow()
int getOldState()
int getNewState()
ADAPTER CLASS
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 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. The table below lists the low level event listener interfaces and their adapters.
The table below shows the adapter classes in java.awt.eventand notes the interface that each
implements.

Example:

Prepared By: Y.Amaraiah


import java.awt.event.*;
import java.applet.*;
import java.awt.*;
public class MyAdapterApplet extends Applet
{
public void init()
{
addMouseListener(new MyAdapter(this));
}
}
class MyAdapter extends MouseAdapter
{
MyAdapterApplet ap;
public MyAdapter(MyAdapterApplet adp)
{
this.ap=adp;
}
public void mouseClicked(MouseEvent e)
{
ap.showStatus(“Mouse Clicked”);
}
}

AWT(Abstract Window Toolkit)


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
Awt Hierarchy Structure

Prepared By: Y.Amaraiah


The Awt supports the following types of controls:
o Labels
o Push buttons
o Check boxes
o Choice list
o Lists
o Scroll bar
 Text editing

Container
The Container is a component in AWT that can contain another component like buttons, text fields,
labels etc. The class that extends Container class are known as container such as Frame, Dialog and
Panel.
Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window.

Prepared By: Y.Amaraiah


Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, text field etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, text field etc
Labels: A label is an object of type Label, and it contains a string, which it displays. Labels are
passive controls that do not support any interaction with the user. Label defines the following
constructors:
Label () throw HeadlessException
Label (String str) throws Headlessexception
Label (string str,int how)throw HeadlessException
The first version creates a blank label. The second version creates a label that contains the string
specified by str. This string is left- justified. The third version creates a label that contains the string
specified by str using alignment specified by how. The value of how must be one three constants:
Label.LEFT, Label.RIGHT, or Label.CENTER.
We can set or change the text in a label by using the setText() method, We can obtain the current
label by calling getText(). The methods are:
void setText(string str)
String getText()
Button: 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.
Button() throw HeadlessException
Button(String str)throws HeadlessException
The first version creates a empty button. The second version creates a button that contains str as a
label.
After a button has been created, you can set its label, by calling setLabel(). We can retrieve its label
by calling getLabel(). The methods are:
void setLabel(String str)
String getLabel()
Here, str the new label for the button.
Handling button: Each time a button is pressed, an action event is generated. This is sent to any
listeners that previously registered an interest in receiving action event notification from that
component. Each listener implements the ActionListener interface. This interface defines the
actionPerformed() methods, which is called when an event occurs. An ActionEvent object is supplied
as the argument to this method. getSource() methods to the button objects that we added to the
window.
Check Boxes: 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. Check boxes are object objects of the Checkbox
class. Checkbox support this constructor:
Checkbox()throw HeadlessException
Checkbox(String str)throw HeadlessException
Checkbox(String str,boolen on)throw HeadlessException
Checkbox(String str,boolen on,CheckboxGroup cbGroup) throw HeadlessException

Prepared By: Y.Amaraiah


Checkbox(String str,CheckboxGroup cbGroup,boolen on) throw HeadlessException
The first form creates a check box whose label is initially blank. The state of this checked box is
unchecked. The second form creates a check box whose label is specified by str. The state of this
checked 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 initially checked; otherwise it is cleared. The fourth and fifth forms creates a
check box whose label specify by the str and whose group is specified by cbGroup.
To retrieve the current state of a check box, call getState(). To set its state, call setState().We can
obtain the current label associated with a check box by calling getLabel().To set the label, call
setLabel().These methods are
boolean getState()
void setState(Boolean on)
String getLabel()
void setLabel(String str)
Handling Checkbox: Each time a check box is selected or deselected, an item event is generated.
This is sent to any listeners that previously registered an interest in receiving action event
notification from that component. Each listener implements the ItemListener interface.
Choice list: The choice class is used to create a pop-up list of items from which the user may choose.
To add a selection to the list, call add().It has this general form:
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the order in which call
to add() occur. To determine which item is currently selected, we may call either getSelectItem() or
getSelectIndex(). These methods are:
String getSelectItem()
int getSelectIndex()
The getSelectItem() methods return a string containing the name of the item.
The getSelectIndex() methods return the index of the item. The first item is at index 0.
By default, the first item added to the list is selected.
To obtain the number of items in the list, call getItemCount(). We can set the currently selected item
using the select() methods with either a zero-based integer index or a string that will match a name
in the list.
int getItemCount()
void select(int index)
void select(String name)
We can obtain the name associated with the item at that index by calling getItem(), which has this
general form :
String getItem(int index)
Here, index specifies the index of the desired element.
Handling Choice List: Each item a choices is selected, an item event is generated. This is sent to any
listeners that previously registered an interest in receiving action event notification from that
component. Each listener implements the ItemListener interface. That interface defines the
itemStateChange() methods. An ItemEvent object is supplied as the argument to this method.
Lists: The List class provides a compact multiple choices, scrolling selection list. The choice object,
which shows only the single selected item in the menu. List provides these constructors:
List() throw headlessException
List(int numRows) throw headlessException

Prepared By: Y.Amaraiah


List(int numRows,boolean multipleSelect ) throw headlessException
The first version creates a list control that allows only one item to be selected at any one item. In
second version, the value of numRows specifies the number of entries in the list that will always be
visible. In the third form, if multipleSelect is true, then the user may select one or more item at a
time.
To add a selection to the list , call add().
void add(String name)
void add(String name,int index)
Here name is the name of the item added to the list. The first form adds item to the end
of the list. The second form adds the item in the index specified by the index.
String getSelectedItem()
int getSelectedIndex()
The getSelectedItem() methods return a string containing the name of the item. If more than one
item is selected, or if no selected, or if no selection has been made, null is returned. getSelectIndex()
methods return the index of the item.
Handling List: We will need to implement the ActionListener interface. Each time a List item is
double clicked, an ActionEvent object is generated. Its getActionCommand() methods can be used to
retrieve the name of the newly selected item.each item an item is selected or deselected with a
single click, an ItemEvent object is generated .getStateChange() can be used to determine whether a
selection or deselection triggered this event.
Scroll Bars: Scroll Bars are used to select continuous values between a specified minimum and
maximum Scroll bars may be oriented horizontally or vertically. Scroll bar are encapsulated by the
Scrollbar class.
Scrollbar define the following constructor :
Scrollbar()throws HeadlessException
Scrollbar(int style)throws HeadlessException
Scrollbar(int style,int initialValue,int thumbSize,int min,int max)throws HeadlessException
The first form creates a vertical scroll bar. The Second and third forms allow we to specify
orientation of the scroll bar. If style is scrollbar.VERTICAL, a vertical scroll bar created. If style is
scrollbar.HORIZONTAL, a horizontal scroll bar created. 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 maximum values for the scroll bar are specified by min and max.
void setValues(int initialvalue,int thumbsize,int min,int max)
The same meaning as they have in the third constructor just described:
To obtain current value of the scroll bar call getValue(). It returns the current string. To set the
current value, call setValue(). These methods are:
int getValue()
void setValue(int newValue)
Here, new value means the new value of the scroll bar. We can also retrieve the minimum and
maximum values via getMinimum() and getMaximum() as shown here:
int getMinimum()
int getMaximum()

Prepared By: Y.Amaraiah


Handling Scroll bar: We need to implement the AdjuestmentListener interface. Each time a user
interface with a scroll bar, an AdjustmentEvent object is generated. Its getAdjustmentType() method
can be used to determine the type of the adjustment.
TextArea: Some time 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. The following constructors
are used for TextArea :
TextArea()throws HeadlessException
TextArea(int numList,int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str,int numLines,int numChars) throws HeadlessException
TextArea(String str,int numLines,int numChars,int sBars) throws HeadlessException
Here, numLines specifies the height, in lines of the text area, and numChars specifies its Width in
character. Initial text can be specified by str. In the fifth form, you can specifies the scroll bars that
you want the control to have sBars must be one of this values.
TextArea is a subclass of TextComponent. Therefore, it supports the getText(), setText(),
getSelectedText(), select(), isEditable(), setEditable() methods.
void append(string str)
void insert(String str,int index)
void replaceRange(String str,int Index,int endIndex)
The append() methods append the string specified by str to the end of the current text.insert()
insert the starting passed in str at the specified index. To replace text, call replaceRange(). It replace
the character from startIndex to the endIndex-1, with the replacement text passed in str.
TextField: The TextField class implements a single-line text-entry area, usually called an edit
control. Text fields allow the user to enter the strings and to edit the text using the arrow keys. cut
and paste keys, and mouse selections. TextFields is a subclass of TextComponent.
TextField()throws HeadlessException
TextField(int numChars)throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str,int numChars) throws HeadlessException
The first version creates a default text field. The second version creates a text fields that is numChars
characters wide. The third version initialize the text field call with the string contain in str. The
fourth form initializes a text field and sets its width.
TextField (and its superclass TextComponent) provides several methods that allow us to utilize a
text field. To obtain the string currently contained in the text field, call getText(). To set the text call
the setText().
String getText()
void setText(String str)
Here, str in the new string.
The user can select a portion of the text in a text filed. Also we can select a portion of text under
program control by using select(). We can obtain the currently selected text by calling
getSelectText().These methods are:
String getSelectText()
void select(int startIndex,int endIndex);
getSelectText() returns the selected text. The select() method select the characters beginning at
startIndex and ending at endIndex -1.

Prepared By: Y.Amaraiah


We can modify the text in the text field by calling the setEditable(). We can determine it by calling
isEditable(). These methods are:
boolen isEditable()
void setEditable(Boolean canEdit)
isEditable() returns true if the text may be changed and false if not. In setEditable(), if canEdit is
true, the text may be changed. If it is false the text cannot be altered.
void setEchoChar(Char ch)
boolen echoCharIsSet()
char getEchoChar()
Here, ch specifies the character to be echoed.
Therefore we can display the echoing of the character as they are typed by calling setEchoChar(). We
can check a text field to see if it is in this mode with the echoCharIsSet() method. We can retrieve the
echo character by calling getEchoChar() method.

Example program using AWT Components


import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

Graphics class
The AWT supports many graphics methods. All graphics are drawn relative to a window. This can
be the main window of an applet, a child window of an applet, or a stand-alone application
window. A graphics context is encapsulated by the Graphics Class and it’s obtained two ways:
It is passed to an applet when one of its various methods, such as paint() or update(),is called.
It is returned by the getGraphics() methods of component.
The Graphics class defines a number of drawing function. Each shape can be drawn edge-only or
filled. Object are drawn and filled in the currently select graphics color, which is black by default. The
several drawing methods :
·Drawing Lines: Line are draw by means of the drawline() method:
void drawLine(int startX,int startY, int endX,endY)

Prepared By: Y.Amaraiah


Therefore drawLine() display a line in the current drawing color that beings at startX startY ends at
endX,endY.
·Drawing Rectangles: The drawRect() and fillrect() methods display an outline and filled rectangle,
respectively.
void drawRect(int top,int left,int width,int height)
void fillRect(int top,int left,int width,int height)
The upper–left corner of the rectangle is at top, left. The dimensions of the rectangle are specified by
width and height. To draw a rounded rectangle, use drawRoundRect() and fillRoundRect(), both are
shown here:
void fillRoundRect(int top,int left,int width,int height,int xDiam,int yDim)
A rounded rectangle has rounded corners; the upper left corner of the rectangle is at top, left. The
dimension of the rectangle is specified by width and height.
·Drawing Ellipses and Circle: To draw an ellipse, use drawOval(). To fill an ellipse, use fillOval().
These methods are shown here:
void drawOval(int top,int left,int width,int height)
void fillOval(int top,int left,int width,int height)
The ellipse is drawn within a bounding rectangle whose upper–left corner is specified by top, left
and whose width and height are specified by width and height.
Drawing polygon: It is possible to draw arbitrarily shaped figures using drawPolygon().
void drawPolygon(int x[],int y[],int numpoints)
void fillPolygon(int x[],int y[],int numpoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays.
The number of points defined by x and y is specified by numpoints.
Working with Color: Java supports color in a portable, device-independent fashion. The AWT color
system allows you to specify any color you want. The color is supported by various hardware
devices. Color is encapsulate by the colorclass.
Color defines several constants (for example Color.black) to specify a number of common colors. We
can also create our own colors, using one of the color constructors.
Color(int red,int green,int blue)
Color(int rgbValue)
Color(float red,float green,float blue)
Color Methods:That color class defines several methods that help manipulate colors:
getRed(),getGreen(),getBlue()
We can obtain the red, green, and blue components of a color independently using getRed(),
getGreen(), and getBlue() as show here:
int getRed()
int getGreen()
int getBlue()
Each of these methods returns the RGB color component found in the invoking Color object in the
lower 8 bit integer.
Setting the Current Graphics color: By default, graphics object are drawn in the current foreground
color. You can change this color by calling the Graphics method setColor()
void setColor(Color newcolor)
You can obtain the current color by calling getColor() shown here:
Color getColor();

Prepared By: Y.Amaraiah


Layout Manager
A layout manager is an object that implements the LayoutManager interface* and determines the
size and position of the components within a container. Although components can provide size and
alignment hints, a container's layout manager has the final say on the size and position of the
components within the container.
Layout means the arrangement of components within the container. In other way we can say that
placing the components at a particular position within the container. The task of layouting the
controls is done automatically by the Layout Manager.
It is very tedious to handle a large number of controls within the container.
Oftenly the width and height information of a component is not given when we need to arrange
them.
Java provide us with various layout manager to position the controls. The properties like size, shape
and arrangement varies from one layout manager to other layout manager. When the size of the
applet or the application window changes the size, shape and arrangement of the components also
changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.
The layout manager is associated with every Container object. Each layout manager is an object of
the class that implements the Layout Manager interface.
BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south and
center.

CardLayout:The CardLayout object treats each component in the container as a card. Only one card
is visible at a time.

Prepared By: Y.Amaraiah


FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.

GridLayout
The GridLayout manages the components in form of a rectangular grid.

GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the component
vertically,horizontally or along their baseline without requiring the components of same size.

Prepared By: Y.Amaraiah


Prepared By: Y.Amaraiah

Anda mungkin juga menyukai