You are on page 1of 49

Event Classes:-

• Events are represented as Objects in Java technology.

• The super class of all event classes is java.util.EventObject. Some of the important classes and

their hierarchy is shown below:

• Some methods related to Events are:

i. Object getSource()

This method is defined in the Event Object class. It returns the object that originated the

event. So if the user has clicked a Push button, the method getSource returns the object

corresponding to Push button is generated.

ii. int getID()


This method returns the integer value corresponding to the type of event. For example if the

user has clicked on the mouse, the method getID returns the integer defined as

MouseEvent.MOUSE_CLICKED.

AWT event Subclasses:-

• The subclasses of AWT Event can be categorized into two groups:

1. Semantic events classes:-


Semantic events directly correspond to high level user interactions with a GUI component. Clicking

of a button is an example of a semantic event. Following event classes are semantic classes:

> ActionEvent

> AdjustmentEvent

> ItemEvent

> TextEvent

2. Low-level events classes:-


Low-level events may get generated for each high level user event. Following event classes are

low level event classes:

> ComponentEvent

> ContainerEvent

> FocusEvent

> KeyEvent

> MouseEvent

> PaintEvent

> WindowEvent
Event types and corresponding EventSource & EventListener

Event Type Event Source Event Listener interface

ActionEvent Button, List, MenuItem, TextField ActionListener

AdjustmentEvent Scrollbar AdjustmentListener

ItemEvent Choice, Checkbox, CheckboxMenuItem, List ItemListener

TextEvent TextArea, TextField TextListener

ComponentEvent Component ComponentListener

ContainerEvent Container ContainerListener

FocusEvent Component FocusListener

KeyEvent Component KeyListener

MouseListener,
MouseEvent Component
MouseMotionListener

WindowEvent Window WindowListener


Event Listener Interfaces and corresponding methods which it defines

Event Listener
Event Listener Methods
interface

ActionListener actionPerformed(ActionEvent evt)

AdjustmentListener adjustmentValueChanged(AjustmentEvent evt)

ItemListener itemStateChanged(ItemEvent evt)

TextListener textValueChanged(TextEvent evt)

componentHidden(ComponentEvent evt), componentMoved(ComponentEvent evt),


ComponentListener
componentResized(ComponentEvent evt), componentShown(ComponentEvent evt)

ContainerListener componentAdded(ContainerEvent evt), componentRemoved(ContainerEvent evt)

FocusListener focusGained(FocusEvent evt), focusLost(FocusEvent evt)

KeyListener keyPressed(KeyEvent evt), keyReleased(KeyEvent evt), keyTyped(KeyEvent evt)

mouseClicked(MouseEvent evt), mouseEntered(MouseEvent evt), mouseExited(MouseEvent


MouseListener
evt), mousePressed(MouseEvent evt), mouseReleased(MouseEvent evt)

MouseMotionListener mouseDragged(MouseEvent evt), mouseMoved(MouseEvent evt)

windowActivated(WindowEvent evt), windowClosed(WindowEvent evt),


WindowListener
windowClosing(WindowEvent evt), windowDeactivated(WindowEvent evt),
windowDeiconified(WindowEvent evt), windowIconified(WindowEvent evt),

windowOpened(WindowEvent evt)

Event Class Name Integer Constants Constructors Methods

ActionEvent class ALT_MASK ActionEvent(Object getActionComman


Src, int type, String cmd, long
CTRL_MASK
when, int
META_MASK modifiers) - command nam
SHIFT MASK
Src - reference getModifiers()
ACTION_PERFORMED Type - event type Cmd - command
When - time modifiers - modifier

- modifiers keys
keys(alt,ctrl,shift,etc) are pressed. getWhen() - time

AdjustmentEvent BLOCK_DECREMENT AdjustmentEvent(Adjustable getAdjustable()


Class BLOCK_INCREMENT src, int id, int type,int data)

TRACK object that genera


UNIT DECREMENT
getAdjustmentTyp
UNIT_INCREMENT -
ADJUSTMENT VALUE CH Adjustment type s
increment, etc.
ANGED

ItemEvent class DESELECTED ItemEvent(ItemSelectable getItem()


src, int type, Objectentry, int -
SELECTED
state) reference to the item
entry
- item generated event state
getItemSelectable

current state of the item


TextEvent class TEXT_VALUE_CHANGED TextEvent(Object src, int type)

ComponentEvent COMPONENT_HIDDEN ComponentEvent(Component src, getComponent()


Class int type)
COMPONENT_MOVED component that gen
COMPONENT_RESIZEDCO
MPONENT_SHOWN
ContainerEvent COMPONENT_ADDED ContainerEvent(Component src, int
type,Component comp) getContainer()
Class COMPONENT_REMOVED
Comp container that caused

component added or removed getChild()


component added or
container

FocusEvent Class FOCUS_GAINED


FocusEvent(Component src, int getOppositeComp
FOCUS_LOST
type,
BooleantemporaryFlag, Component Opposite componer
other)
isTemporary()
temporaryFlag
true if change is te
- true if focus event is
temporary
other

- other component that lost


or gainedfocus.
InputEvent Class ALT_DOWN_MASK isAltDown()
ALT_GRAPH_DOWN_MASK
BUTTON1_DOWN_MASKB - to know the k
UTTON2_DOWN_MASKBU
TTON3_DOWN_MASKCTR isAltGraphDown()
L_DOWN_MASK
M ETA_DOWN_MASK isControlDown()
SHIFT_DOWN_MASK
isMetaDown()

isShiftDown()

KeyEvent Class KeyEvent(Component src, int type, getKeyChar()


KEY_PRESSED long when, int modifiers, int code,
KEY_RELEASED char ch)
- returns chara<
KEY_TYPED
Code
VK_0 to VK_9
VK_A to VK_Z VK_ENTER getKeyCode()
- virtual key code (VK_UP)
VK_ESCAPE - returns key code
VK_CANCEL ch- character equivalent
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
VK_SHIFT
VK_ALT
VK_CONTROL
MouseEvent class MOUSE_CLICKED MouseEvent(Component src, getX() getXY() g<
MOUSE_DRAGGED int type, long when,int modifiers, int coordinates
MOUSE_ENTERED x, int y, int
MOUSE_EXITED clicks, Booleantriggers popup) getClickCount()isP
MOUSE_MOVED n() - returns the bu
MOUSE_PRESSED x,y - coordinates clicks - no. of event(NO
mouse clicks triggers popup - BUTTON,BUTTON1
MOUSE_RELEASED indicates if the event causes a
popup menu

WindowEvent WINDOW_ACTIVATED WindowEvent(Windows src, getWindow()


class WINDOW_CLOSED int type, Windowother, int getOppositeWindo
WINDOW_CLOSING fromState, int toState) getOldState()
WINDOW_DEACTIVATED getNewState()
WINDOW_GAINED_FOCU Other - opposite window when a
S focus event occurs fromState -
WINDOW_LOST_FOCUS prior state toState - new state
WINDOW_OPENED
WINDOW_STATE_CHANGED
ActionEvent class

An action event is generated when a button is pressed; a list item is double clicked.
• Constructors:

i. ActionEvent(Object src, int type, String cmd)


ii. ActionEvent(Object src, int type, String cmd, int modifiers)
iii. ActionEvent(Object src, int type, String cmd, long when, int modifiers)

Here
src - is reference to the object that generated this event. type - is type of
event. cmd - is command string.
modifiers - indicates which modifier keys(ALT, CTRL, META, and /or SHIFT)
were pressed when event was generated. when - parameter specifies when
the event occurred.

• Methods:

1. getActionCommand() - obtain command name for invoking ActionEvent


object.
2. -returns a value that indicate which modifier keys(ALT, CTRL,
getModifiers()
META, and /or SHIFT) were pressed when event was generated.
3. getWhen()-return
the time at which the event took place. This is called
event's timestamp.

Adjustment Event class

Adjustment event is generated by a scrollbar.

• Constructor:
AdjustmentEvent(Adjustable src, int id, int type, int data)

src - is reference to the object that generated this event.


id - equals ADJUSTMENT_VALUE_CHANGED
type - is type of an event and its associated data is 'data'.
• Constants:

BLOCK_DECREMENT:-clicked inside to decrease its value. BLOCK_INCREMENT:-clicked inside to


increase its value.
TRACK:-slider dragged
UNIT_DECREMENT:-button at the end of scrollbar was clicked to decrease its value.
UNIT_INCREMENT:-button at the end of scrollbar was clicked to increase its value.

• Methods:

1. Adjustable getAdjustable():-returnsobject that generated the event.


2. int getAdjustmentType():-returns one of the constants.
3. int getValue():-obtain the amount of adjustment.

Item Event class


Generated when checkbox or a list item is clicked or when a checkbox menu item is
selected or deselected.
• Constructor:
ItemEvent(ItemSelectable src, int type, Object entry, int state)

src - is the reference to the component that generates an event. type - type of event is
specified by 'type'.
Entry - item that generated, the item event is parsed. state - current state of the item.

Methods:
1. getItem()-Obtain a reference to the item that generated an event.
2. getItemSelectable()-Obtain a reference to a ItemSelectable object. Lists and
choices are example of user interface elements that implement the
ItemSelectable interface.
3. getStateChange()-return the state change(selected or deselected)

Text Event class

Generated when the value of textarea or textfield is changed.

• Constructor:

TextEvent(Object src, int type)

src - is the reference to the object. type - is type of the object.


• Constants:
TEXT VALUE CHANGED

Component Event class


It is generated when a component is hidden, moved, resized or becomes visible.
• Constructor:
ComponentEvent(Component src, int type)

Src - is the reference to the object that generated this event. type - type of event
is specified by 'type'.
• Constants:

COMPONENT_HIDDEN: the
component is hidden. COMPONENT_MOVED: the component is
moved. COMPONENT_RESIZE: the component is resized. COMPONENT_SHOWN: the
component becomes visible.
• Methods:

1. getComponent()-returns the component that generated an event.


Focus Event class

Event is generated when a component gains or losses input focus.

• Constructors:

i. FocusEvent(Component src, int type)


ii. FocusEvent(Component src,int type,boolean temporaryFlag)
iii. FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
src - is the reference to the component that generated this event.
type - is the type of event.
temporaryFlag - is set to true if the FocusEvent is temporary otherwise it is set to
false.
other - which is involved in focus change, called the opposite component is passed in
other.
• Methods:

1. Component getOppositeComponent()-The opposite component is returned.


2. isTemporary()-returns true if the change is temporary, otherwise it returns false.

Key Event class

Event occurs, when keyboard input occurs.

• Constructors:

i. KeyEvent(Component src, int type, long when, int modifiers, int code)
ii. KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
• Constants:

KEY_PRESSED
KEY_RELEASED
KEY_TYPED: event occurs when a character is generated, not all key presses result in
character.
• Methods:

1. char getKeyChar()-returns character that was entered.


2. int getKeyCode()-returns the key code
If no valid character available, returns CHAR_UNDEFINED.

Mouse Event class


Generated when the mouse is dragged, moved, clicked, pressed or released,also
generated when mouse enters or exits a component.
• Constructor:

MouseEvent(Component src,int type,long when,int modifier,int x,int y,int clicks,Boolean triggersPopup)

src - is reference to the component that generated an event. type - type of an event is
'type'.
when - the system time at which the mouse event occurred is passed in 'when'.
Modifiers - argument indicates which modifiers were pressed when a mouse event
occurred.
triggersPopup - flag indicates if this event causes a pop-up menu to the button that
caused the event to be specified.
• Constants:

MOUSE_CLICKED-the user clicked the mouse.


MOUSE_DRAGGED-the user dragged the mouse.
MOUSE_ENTERED-the mouse entered the component. MOUSE_EXITED-the mouse
exited from a Component. MOUSE_MOVED-the mouse moved.
MOUSE_PRESSED-the mouse was pressed.
MOUSE_RELEASED-the mouse was released.
MOUSE_WHEEL-the mouse wheel was moved.
• Methods:

1. The argument x & y are added to the coordinates


void translate(int x,int y):-
2. int getClickCount():- Obtains the number of mouse clicks for this event.
3. boolean isPopupTrigger():- Tests if this event causes a pop-up menu to appear
on this platform.
4. int getButton():- returns a value that represents the button that caused the
event. It can be NOBUTTON, BUTTON1, BUTTON2, and BUTTON3.
NOBUTTON indicates that no button was pressed or released.

Window Event class

It is generated for window and its subclasses.

• Constructors:

i. WindowEvent(Window src,int type)


ii. WindowEvent(Window src, int type, Window other)
iii. WindowEvent(Window src, int type, int fromstate, int tostate)
iv. WindowEvent(Window src, int type, Window other, int fromstate, int tostate)
Src - reference to the object that generated event. type - type of the event.
other - specifies opposite window when the event occurs. fromstate - specifies the prior
state of window. tostate - specifies new state that will take place when a window
change occurs.
• Constants:

WINDOW_ACTIVATED-window activated.
WINDOW_CLOSED-window closed.
WINDOW_CLOSING-the user requested that the window be closed.
WINDOW_DEACTIVATED-window deactivated. WINDOW_DEICONIFIED-window
deiconified. WINDOW_GAINED_FOCUS-window gained input focus.
WINDOW_ICONIFIED-window was iconified. WINDOW_LOST_FOCUS-window lost
focus.
WINDOW_OPENED-window was opened. WINDOW_STATE_CHANGED-window state
changed.
Window is subclass of Component event.
• Methods:

getWindow()-returns window object that generates an event.


Event Listener Interfaces:-

• It is used to process events.


• Eg:- Clicking button, typing text in textfield
• The event listener's job is to catch those events and do something with them.
• Java provides a good range of event listener interface to implement them.
• To use listener :
> Specify that the class implements the interface (Listener)
> Register the listener on one or more components
> Implements all methods from listener
• Types of the listeners are as:

1. ActionListener Interface:-
■ It defines the method that is invoked when an action event occurs.
■ void actionPerformed(ActionEvent ae)

2. AdjustmentListener Interface:-
■ It defines the method that is invoked when an adjustment event occurs.
■ void adjustmentValueChanged(AdjustmentEvent ae)

3. ComponentListener Interface:-
■ It defines four methods that are invoked when a component is resized, moved, shown, or hidden.
■ void componentResized(ComponentEvent ce)
■ void componentMoved(ComponentEvent ce)
■ void componentShown(ComponentEvent ce)
■ void componentHidden(ComponentEvent ce)

4. ContainerListener Interface:-
■ It defines two methods that are invoked when a component is added to a container and when a
component is removed from a container.
■ void componentAdded(ContainerEvent ce)
■ void componentRemoved(ContainerEvent ce)

5. FocusListener Interface:-
■ It defines two methods that are invoked when a component gained a focus and when a component loses
a focus.
■ void focusGained(FocusEvent fe)
■ void focusLost(FocusEvent fe)

6. ItemListener Interface:-
■ It defines a method that is invoked when the state of an item changes.
■ void itemStateChanged(ItemEvent ie)

7. KeyListener Interface:-
■ It defines three methods that are invoked when a key of a keyboard is pressed, released and
typed.
■ void keyPressed(KeyEvent ke)
■ void keyReleased(KeyEvent ke)
■ void keyTyped(KeyEvent ke)

8. MouseListener Interface:-
■ It defines five methods that are invoked when mouse is entered, exited, pressed, released
and clicked.
■ void mouseEntered(MouseEvent me)
■ void mouseExited(MouseEvent me)
■ void mousePressed(MouseEvent me)
■ void mouseReleased(MouseEvent me)
■ void mouseClicked(MouseEvent me)

9. MouseMotionListener Interface:-
■ It defines two methods that are invoked when mouse is moved and dragged.
■ void mouseMoved(MouseEvent me)
■ void mouseDragged(MouseEvent me)

10. WindowListener Interface:-


■ It defines seven methods that are invoked when window is activated, deactivated, opened,
closed, closing, iconified and deiconified.
■ void windowActivated(WindowEvent we)
■ void windowDeactivated(WindowEvent we)
■ void windowOpened(WindowEvent we)
■ void windowClosing(WindowEvent we)
■ void windowClosed(WindowEvent we)
■ void windowIconified(WindowEvent we)
■ void windowDeiconified(WindowEvent we)
Program on MouseListener

import java.awt.*; import java.awt.event.*; import java.applet.*;


/*
<applet code="MouseListenerDemo" width=300 height=200>
</applet>
*/
public class MouseListenerDemo extends Applet implements MouseListener,
MouseMotionListener {
String msg=""; int x=10, y=10;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
msg="Mouse Clicked"; repaint();
}

public void mouseEntered(MouseEvent me) {


msg="Mouse Entered"; repaint();
}

public void mouseExited(MouseEvent me)


{
msg="Mouse Exited"; repaint();
}

public void mousePressed(MouseEvent me) {

x=me.getX();
y=me.getY();

msg="Mouse down"; repaint();


}

public void mouseReleased(MouseEvent me)


{
x=me.getX(); y=me.getY(); msg="Mouse up";
repaint();
}

public void mouseDragged(MouseEvent me)


{
x=me.getX();
y=me.getY();
msg="*";
showStatus("Dragging mouse at "+x+", "+y);
repaint();
}

public void mouseMoved(MouseEvent me)


{
x=me.getX();
y=me.getY();
showStatus("Moving mouse at "+x+", "+y);
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg, x, y);
}
}

Program on KeyListener:

import java.awt.*; import


java.awt.event.*; import
java.applet.*;
/*
<applet code="KeyListenerDemo" width=300 height=200>
</applet>
*/
public class KeyListenerDemo extends Applet implements KeyListener {
String msg=""; int x=10, y=20;

public void init()


{
addKeyListener(this);
requestFocus();
}

public void keyPressed(KeyEvent ke) {


showStatus("Key Down"); int
k=ke.getKeyCode();

switch(k)
{

case KeyEvent.VK_F1:

msg+="<F1>";
break;

case KeyEvent.VK_F2:
msg+="<F2>";
break;
case KeyEvent.VK_F3:
msg+="<F3>";
break;

case KeyEvent.VK_PAGE_DOWN:
msg+="<pg down>";
break;

case KeyEvent.VK_PAGE_UP:
msg+="<pg up>";
break;

case KeyEvent.VK_LEFT:
msg+="<left arrow>";
break;

case KeyEvent.VK_RIGHT:
msg+="<right arrow>"; break;
}
repaint();
}

public void keyReleased(KeyEvent ke)


{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg+=ke.getKeyChar();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg, x, y);
}
}

Program on WindowListener:-

import java.awt.*; import java.awt.event.*;

public class WindowListenerDemo extends Frame implements


WindowListener {
public WindowListenerDemo()
{
addWindowListener(this);
}

public void windowActivated(WindowEvent we)


{
System.out.println("Window Activated");
}

public void windowDeactivated(WindowEvent we)


{
System.out.println("Window Deactivated");
}

public void windowIconified(WindowEvent we)


{
System.out.println("Window Iconified");
}

public void windowDeiconified(WindowEvent we)


{
System.out.println("Window Deiconified");
}

public void windowOpened(WindowEvent we)


{
System.out.println("Window Opened");
}

public void windowClosing(WindowEvent we)


{
System.out.println("Window Closing");
}

public void windowClosed(WindowEvent we)


{
System.out.println("Window Closed");
}
public static void main(String arg[])
{
WindowListenerDemo wd=new WindowListenerDemo();
}
}

Adapter Class:-

• It provides the default implementation of all methods in an event listener interface.


• It provides an empty implementation of all methods in an event listener interface i.e. this class itself
write definition for methods which are present in particular event listener interface.
• These classes are very useful when you want to process only few of the events that are handled by a
particular event listener interface.
• Every listener that includes more than one abstract method has got a corresponding adapter class.
• We can define a new class by extending one of the adapter classes and implement only those events
in which we are interested.
Example:-

import java.awt.*; import java.awt.event.*; import java.applet.*;

/* <applet code="AdapterDemo" height=200 width=200>


</applet>*/

public class AdapterDemo extends Applet {


public void init()
{
addMouseListener(new MyMouseAdapter(this));
}
}

class MyMouseAdapter extends MouseAdapter {


AdapterDemo ad;

public MyMouseAdapter(AdapterDemo d)
{
ad=d;
}

public void mouseClicked(MouseEvent me)


{
ad.showStatus("Mouse Clicked");
}
}

Inner Classes:-

• An inner class is a class declared entirely within the body of another class or interface.
• It is nothing but a nested class.
• It can be used to simplify the code when using event adapter classes.
Example:-

import java.awt.*; import java.awt.event.*; import java.applet.*;

/* <applet code="InnerClassDemo" height=200 width=200>


</applet>*/

public class InnerClassDemo extends Applet {


public void init()
{
addMouseListener(new MyMouseAdapter());
}

class MyMouseAdapter extends MouseAdapter {


public void mousePressed(MouseEvent me)
{
showStatus("MousePressed");
}
}
}

Anonymous Inner Class:-

• It enable user to make a code more concise.


• They enable you to declare and instantiate a class at the same time.

• They are like local classes except that they do not have a name.
Example:-

import java.awt.*; import java.awt.event.*; import java.applet.*;

/* <applet code="AnonymousInnerClassDemo" height=200 width=200> </applet>*/

public class AnonymousInnerClassDemo extends Applet {

public void init()


{
addMouseListener(new MyMouseAdapter(){ public void mousePressed(MouseEvent me)
{
showStatus("MousePressed");
} } );
}
}

What is GUI:-

• It is a graphical user interface to a computer.


• It is a medium provided by software for a human to interact with the computer.\
• GUI provides us images, buttons, colors for easy understanding and for handling event using
keyboard and mouse.
• Advantages of GUI:

> It is easier to learn and use


> GUI provides immediate visual feedback to user of his every action.
> With visual support, GUI simplifies the way to take advantage of multitasking facility of OS.
> It is now used in almost every kind of software.
> GUI gives more help to understand the use of OS and its facilities even if user is new to
computer.

• Java facilitate JFC to us for developing GUI components


• JFC is Java Foundation Classes, which include a group of features to help developer for building
GUI.

AWT:-

• Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application 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 uses the resources of system.
• The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.

Window Fundamentals:

The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level.

1. Component:-
• It 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 number of public methods that are responsible for managing events.

2. Container:-
• The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc.
• The classes that extends Container class are known as container such as Frame, Dialog and Panel.
• It is responsible for laying out any components that it contains.

3. Panel:-
• The Panel is the container that doesn't contain title bar and menu bars.
• It can have other components like button, textfield etc.
• As a component it can be added to another container and as a container it can be added with
components.
• We can also nest the Panels.

4. Window:-
• Window comes with no borders and no menubar.

• The default layout for a window is BorderLayout.

• A window must have either a frame, dialog, etc.

5. Frame:-
• The Frame is the container that contain title bar and can have menu bars.

• It can have other components like button, textfield etc.

6. Canvas:-
• It represents a blank rectangular area of the screen onto which the application can draw.
• It is designed for displaying simple graphics.
• The paint() must be overridden in order to perform custom graphics.

Frame:-
• It works like the main window where components are added.

• It creates a standard style window.

• Constructors:¬
> Frame () - It creates a standard window without title.
> Frame (String title) - It creates a standard window with title.

• Methods:¬
> void setSize(int width, int height) - It is used to set the dimensions of the window.
> void setVisible(boolean flag) - The component is visible if the flag value is true. Otherwise it is hidden.
> void setTitle(String str) - It allows the user to additionally set the title to the frame.
> void setLocation(int x, int y) - It allows to set the x and y co-ordinates of Frame.

Example:-

import java.awt.*;

class FrameDemo extends Frame {


FrameDemo()
{
setSize(200, 200); setLocation(100, 100); setVisible(true);
setTitle("My first Frame Program");
}

public static void main(String arg[])


{
FrameDemo fd=new FrameDemo();
}
}

Control Fundamentals:-

AWT provides several controls through the classes. Controls are the components that allow a user to interact
with our application in various ways.

1. Label:-

It contains a string which it displays.


• Labels are passive controls that do not support any interaction with the user.

• Constructors:¬
> Label () - It creates a blank label.
> Label (String str) - It creates a label that contains a string specified by str.
> Label (String str, int how) - It creates label that contains a string specified by str using alignment
specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or
Label.CENTER.
• Methods:¬
> void setText(String str) - Assigns a new string to label.
> String getText() - reads the string from label.
> void setAlignment(int how) - sets the alignment as LEFT, RIGHT, CENTER to label.
> int getAlignment() - reads the alignment of a label.
Example:-

import java.awt.*;

public class LabelDemo extends Frame {


Frame f;
Label l1, l2, l3;

public LabelDemo()
{
f=new Frame();

l1=new Label("One"); l2=new Label("Two"); l3=new Label("Three");

11. setBounds(10, 10, 200, 200);


12. setBounds(20,20,300,300);

setLayout(null); setSize(200, 200); setVisible(true);

add(l1);
add(l2);
add(l3);

}
public static void main(String a[])
{
LabelDemo ld=new LabelDemo();
}
}

2. Button:-
• It is a component that contains a label and that generates an event when it is pressed.
• Constructors:¬
> Button() - It creates an empty button.
> Button(String str) - It creates a button that contains str as a label.
• Methods:¬
> void setLabel(String str) - sets label of a button.
> String getLabel() - gets a label of a button.

Example:

import java.awt.*; import java.awt.event.*;

public class ButtonDemo extends Frame implements ActionListener {


Button b1, b2;
Label l1;

public ButtonDemo(String str)


{
super(str);

b1=new Button("one"); b2=new Button("two");

l1=new Label();

setLayout(new FlowLayout());

add(b1);
add(b2);

add(l1);
bl.addActionListener(this);
b2.addActionListener(this);

setSize(200, 200); setVisible(true); setLocation(50, 50);


}

public void actionPerformed(ActionEvent ae)


{

if(ae.getSource()==b1)

ll.setText("Button one is clicked"); if(ae.getSource()==b2)

l1.setText("Button two is clicked");


}

public static void main(String arg[])


{
ButtonDemo bd=new ButtonDemo("First program for Button");
}
}

3. Checkbox:-
• It is used when there are multiple options and multiple selections to turn an option on or off.
• It is a small box that can either contain a check mark or not.
• Constructors:¬
> Checkbox() - create checkbox with blank label.
> Checkbox(String str) - create a checkbox with str label.
> Checkbox(String str, boolean on) - create a checkbox with string label with checked or unchecked.

• Methods:¬
> boolean getState() - gives the state as checked or unchecked.
> void setState(boolean on) - sets the state as checked or unchecked.
> String getLabel() - reads the label of checkbox.
> void setLabel(String str) - assigns the label to checkbox.
Example:-
import java.awt.*; import java.awt.event.*;
public class CheckboxDemo extends Frame implements ItemListener {
Checkbox cb1, cb2, cb3, cb4;
Label l1;

public CheckboxDemo(String str)


{
cb1=new Checkbox("One"); cb2=new Checkbox("Two"); cb3=new
Checkbox("Three"); cb4=new Checkbox("Four");

l1=new Label();

setLayout(new FlowLayout());

add(cb1);

add(cb2);
add(cb3);
add(cb4);

add(l1);

setSize(200, 200); setVisible(true); setLocation(50, 50);

cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
cb4.addItemListener(this);
}

pubic void itemStateChanged(ItemEvent ie)


{
if(ie.getItemSelectable()==cb1)
l1.setText("Checkbox 1 is clicked"); if(ie.getItemSelectable()==cb2)
l1.setText("Checkbox 2 is clicked"); if(ie.getItemSelectable()==cb3)
l1.setText("Checkbox 3 is clicked"); if(ie.getItemSelectable()==cb4)
l1.setText("Checkbox 4 is clicked");
}

public static void main(String arg[])


{
CheckboxDemo cd=new CheckboxDemo("First program for Checkbox");
}
}

4. CheckboxGroup:-
• It is possible to create a set of mutually exclusive checkboxes in which one and only one checkbox in the
group can be checked at any one time.
• It is also known as RadioButton.
• Constructors:¬
> Checkbox(String str, boolean on, CheckboxGroup cbg)
> Checkbox(String str, CheckboxGroup cbg, boolean on)
These constructors create a checkbox whose label is as str and whose group is specified by cbg, the Boolean
value determine the initial state of checkbox.
• Methods:¬
> Checkbox getSelectedCheckbox() - reads the selected radio button from group.
> void setSelectedCheckbox(Checkbox c) - selects radio button option of a group.
Example:-
import java.awt.*; import java.awt.event.*;

public class CheckboxGroupDemo extends Frame implements ItemListener {


CheckboxGroup cbg;
Checkbox cb1, cb2, cb3, cb4;
Label l1;

public CheckboxGroupDemo(String str)


{
super(str);

cbg=new CheckboxGroup();

cb1=new Checkbox("One", false, cbg); cb2=new Checkbox("Two", false, cbg); cb3=new Checkbox("Three",
false, cbg); cb4=new Checkbox("Four", false, cbg);
l1=new Label();

setLayout(new FlowLayout());

add(cbl);
add(cb2);
add(cb3);
add(cb4);
add(l1);

setSize(200, 200); setLocation(200, 300); setVisible(true);


}

public void itemStateChanged(ItemEvent ie)


{
l1.setText("Radio Button:"+((Checkbox)ie.getItemSelectable()).getLabel()+"
clicked");
}

public static void main(String arg[])


{
CheckboxGroupDemo cbgd=new CheckboxGroupDemo();
}
}

5. Choice:-
• It provides drop down control for the option selection.
• It takes up only enough space to show the currently selected item.
• When user clicks on it, the whole list of choices pops up, and a new selection can be made.
• Choice class uses default constructor to create it.
• Methods:¬
> void add(String name) - it adds an item in the list.
> String getSelectedItem() - it reads the selected item from the list.
> int getSelectedIndex() - it reads the selected item index number from the list.
> int getItemCount() - it gives the number of items in the list.
> String getItem(int index) - it reads the item at given index.

Example:-
import java.awt.*;
import java.awt.event.*;

public class ChoiceDemo extends Frame implements ItemListener {


Choice os, browser;
Frame f;
String msg=" ";

public ChoiceDemo()
{
super("Program using choice control");

f=new Frame(); setSize(200, 200);


setVisible(true); setLayout(new
FlowLayout());

os=new Choice(); browser=new Choice();

os.add("Windows XP"); os.add("Windows


NT"); os.add("Solaris"); os.add("Mac OS");

browser.add("Netscape Navigator");
browser.add("Internet Explorer");
browser.add("Opera"); browser.add("Mozilla
Firefox"); //browser.select("Opera");

add(os);
add(browser);

os.addItemListener(this);
browser.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
repaint();

}
public void paint(Graphics g)
{
msg="Current OS:";
msg+=os.getSelectedItem();
g.drawString(msg, 200, 200);

msg="Current browser:";
msg+=browser.getSelectedItem();
g.drawString(msg, 200, 300);
}

public static void main(String a[])


{
ChoiceDemo cd=new ChoiceDemo();
}
}

6. List:-
• It provides a compact, multiple choices, scrolling selection list.
• We can select multiple options from the list.
• Constructors:¬
> List() - it creates normal list with single selection capability.
> List(int numrows) - creates a normal list with only single selection capability with specified number of rows.
> List (int numrows, Boolean multiselect) - create a list with specified number of rows with unabling or
disabling the multiple selection.
• Methods:¬
> void add(String name) - to add an item in the list.
> void add(String name, int index) - to add an item in the list at specified index.
> String getSelectedItem() - Reads the current selection from the list.
> int getSelectedIndex() - gives the index number of current selection.
> int getItemCount() - gives number of items present in the list.
> String getItem(int index) - reads the item from the list at specified index.

Example:

import java.awt.*; import java.awt.event.*;

public class ListDemo extends Frame implements ActionListener {

Frame f;
List 11;
String msg=" ";
Label l;

public ListDemo()
{
super("Program using List"); f=new Frame();
setSize(200, 200); setVisible(true); setLayout(new
FlowLayout());

l1=new List(3, true);


l1.add("Red");
l1.add("Green");
l1.add("Blue");
l1.add("Yellow");

l1.select(2);
add(l1);

l1.addActionListener(this);

l=new Label(); add(l);


}

public void actionPerformed(ActionEvent ae) {


int idx[];
msg="Current selected color is:";
idx=l1.getSelectedIndexes(); for(int i=0; i<idx.length;
i++)
msg+=l1.getItem(idx[i])+" "; l.setText(msg);
}

public static void main(String a[])


{
ListDemo ld=new ListDemo();
}

7. Scrollbar:-
• When the contents of a window are too large to be displayed entirely within the window, a scroll
bar will appear.
• The scroll bar contains a slider that the user can click and drag to scroll through the window.
• It is a vertical bar on the right side of a window or a horizontal bar at the bottom of a window that
is used to move the window contents up and down or left and right.
• Constructors:¬
> Scrollbar() - it creates a vertical scroll bar.
> Scrollbar(int style) - it creates a scrollbar with specified orientation.
> Scrollbar(int style, int initialvalue, int thumbsize, int min, int max) - it creates a scrollbar with
specified orientation, sets the initial value, represents number of unit by thumbsize, minimum and
maximum value.
• Methods:¬
> void setValues(int initialvalue, int thumbsize, int min, int max)
> int getValue() - it returns current value of scrollbar.
> void setValue(int newValue) - sets the newValue for the scrollbar.
> int getMinimum() - returns the minimum value of scrollbar.
> int getMaximum() - returns the maximum value of scrollbar.
> void setUnitIncrement(int newIncr) - it allows to change increment value
> void setBlockIncrement(int newIncr) - it allows to change block increment value
Example:-

import java.awt.*; import java.awt.event.*;

public class ScrollBarDemo extends Frame implements AdjustmentListener, MouseMotionListener {


Scrollbar vs, hs;
String msg=" ";

public ScrollBarDemo()
{
//int width=Integer.parseInt(getParameter("width"));
//int height=Integer.parseInt(getParameter("height")); setLayout(new FlowLayout());

vs=new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 10); hs=new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 1,


10);

add(vs);
add(hs);

vs.addAdjustmentListener(this);
hs.addAdjustmentListener(this);

addMouseMotionListener(this);

setVisible(true); setSize(200, 200);


}

public void adjustmentValueChanged(AdjustmentEvent ae) {


repaint();
}

public void mouseDragged(MouseEvent me)


{
int x=me.getX(); int y=me.getY();

vs.setValue(y);
hs.setValue(x);

repaint();
}

public void mouseMoved(MouseEvent me)


{
}

public void paint(Graphics g)


{
msg="Vertical: " +vs.getValue(); msg+=" ,
Horizontal:"+hs.getValue();

g.drawString(msg, 150, 150);


}

public static void main(String arg[])


{
ScrollBarDemo sd=new ScrollBarDemo();

}
}
8. TextField:-
• It is a single line text entry area.
• It allows the user to enter strings and to edit the text using the arrow keys, etc.
• It is a subclass of TextComponent.
• Constructors:¬
> TextField() - it creates default text field.
> TextField(int numchars) - it creates a textfield that is numchars characters wide.
> TextField(String str) - it creates a textfield with the string str.
> TextField(String str, int numchars) - it creates a textfield with string and sets its width with numchars.
• Methods:¬
> String getText() - to read the text from textfield
> void setText(String str) - to set the text to textfield.
> String getSelectedText() - reads only the selected text from the textfield.
> void select(int startindex, int endindex) - reads the currently selected text.
> boolean isEditable() - specify whether the textfield is editable or not.
> void setEditable(Boolean canEdit) - sets the text field editable.
> void setEchoChar(Char ch) - to disable the echoing of the characters as they are typed.
> boolean echoCharIsSet() - checks the textfield to see if it is in echochar mode.
> char getEchoChar() - it retrieves the echo character.
Example:
import java.awt.*; import java.awt.event.*;

class TextFieldDemo extends Frame implements ActionListener {


Label l1, l2;
TextField name, pass;

TextFieldDemo()
{

setLayout(new FlowLayout());
setVisible(true);
setSize(200, 200);

l1=new Label("Name"); l2=new Label("Password:");

name=new TextField(15); pass=new TextField(10); pass.setEchoChar('*');

add(l1);
add(name);
add(l2);
add(pass);

name.addActionListener(this);
pass.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
repaint();
}

public void paint(Graphics g)


{
g.drawString("Name:"+name.getText(), 10,50);
g.drawString("Selected text in Name:"+name.getSelectedText(), 10, 80);
g.drawString("Password:"+pass.getText(), 10, 110);
}

public static void main(String arg[])


{
TextFieldDemo td=new TextFieldDemo();
}
}

9. TextArea:-
• It is a multiline editor.
• Constructors:¬
> TextArea() - it creates default textarea.
> TextArea(int numlines, int numchars) - it creates textare with specified number of
lines i.e. height and specified number of characters i.e. width.
> TextArea(String str) - creates textarea with specified string.
> TextArea(String str, int numlines, int numchars) - creates textarea with specified string,
height and width.
> TextArea(String str, int numlines, int numchars, int sBars) - creates textarea with
specified string, height, width and orientation of scrollbar.
• Methods:> String getText() - to read the text from textfield
> void setText(String str) - to set the text to textfield.
> String getSelectedText() - reads only the selected text from the textfield.
> void select(int startindex, int endindex) - reads the currently selected text.
> boolean isEditable() - specify whether the textfield is editable or not.
> void setEditable(Boolean canEdit) - sets the text field editable.
> void append(String s) - appends the string specified by s to the end of the current text.
> void insert(String s, int index) - inserts the string passed in s at the specified index.
> void replaceRange(String s, int startIndex, int endIndex) - replaces the character from
startIndex to endIndex-1 with the replacement text passed in s.
Example:-
import java.awt.*;
import java.awt.event.*;

class TextAreaDemo extends Frame


{
TextArea t;

TextAreaDemo()
{
String val="Textareas are almost self contained controls.
Your program incurs virtually no management overhead.
Textareas only generate got focus and lost focus events.
Normally your program simply obtains the current text when it is
needed.";

t=new TextArea(val, 30, 30);

setLayout(new FlowLayout());
setVisible(true); setSize(200, 200);

add(t);
}
public static void main(String arg[])
{
TextAreaDemo td=new TextAreaDemo();
}
}

Layout Managers:-

• Sometimes we want more control over how GUI components are placed on our programs.
Layout managers are one way to do this.
• There are alternatives to layout managers which includes:
> Specifying the exact position of each component i.e. using setBounds().
> Using tools that design GUI's and generate code for absolute positioning.
• There are different types of layout managers are as:

1. FlowLayout:
■ This is default layout manager for applet.
■ All GUI components are simply placed on the GUI from left to right in the order as they are added.
■ Constructors:
> FlowLayout() - it creates default layout which centers components and leaves five pixels of space between
each component.
> FlowLayout(int how) - it specify how each component is aligned.
> FlowLayout(int how, int horz, int vert) - it specify the horizontal and vertical space between components.
■ Syntax:
setLayout(new FlowLayout());
■ All GUI components are aligned centered in a FlowLayout by default. We can change the alignment using
method setAlignment() or we can pass alignment as: setLayout(new
FlowLayout(FlowLayout.RIGHT));
■ Valid alignments are:
> FlowLayout.LEFT
> FlowLayout.CENTER
> FlowLayout.RIGHT

Example:-
import java.awt.*; import java.awt.event.*;

class FlowLayoutDemo extends Frame {


FlowLayoutDemo()
{
setLayout(new FlowLayout(FlowLayout.RIGHT));

setSize(200, 200); setVisible(true);

for(int i=0; i<5; i++)


add(new Label("Demo #"+i));
}

public static void main(String arg[])


{
FlowLayoutDemo fd=new FlowLayoutDemo();
}
}

2. BorderLayout:
■ This is default layout manager for Frame which adds the component in Center by default.
■ It breaks the field up into five areas: north, south, east, west and center.
■ Constructors:
> BorderLayout() - it creates a default border layout.
> BorderLayout(int horz, int vert) - it allows to specify the horizontal and vertical space between
components.
■ Syntax:
setLayout(new BorderLayout());
■ We can set the alignment while adding the component as: add(button1, BorderLayout.NORTH);
Example:-

import java.awt.*; import java.awt.event.*;

public class BorderLayoutDemo extends Frame


{

Frame f;

public BorderLayoutDemo()

super("Program for BorderLayout");

setSize(200, 200); setVisible(true);

setLayout(new BorderLayout());

add(new Button("Top"), BorderLayout.NORTH); add(new

Button("Down"), BorderLayout.SOUTH); add(new

Button("Right"), BorderLayout.EAST); add(new

Button("Left"), BorderLayout.WEST);

String msg="The BorderLayout class implements a common layout style for top-level
windows. It has four narrow, fixed-width components at the edges and one large area in the center.";

add(new TextArea(msg), BorderLayout.CENTER);

/*public Insets getInsets()


{

return new Insets(100, 100, 100, 100);

}*/

public static void main(String a[])

BorderLayoutDemo bd=new BorderLayoutDemo();

getInsets() methods leave a small amount of space between the container that holds components
and the window that contains it.
It returns Insets object that contains the top, bottom, left and right inset to be used.

3. GridLayout:
■ It lays out component in a two dimensional grid.
■ When we instantiate a GridLayout, we define the number of rows and columns.
■ Specifying number of rows as zero allows for unlimited length columns.
■ Specifying number of columns as zero allows for unlimited length rows.
■ Constructors:
> GridLayout() - it creates a single column grid layout.
> GridLayout(int rows, int columns) - It creates a grid layout with the specified number
of rows and columns.
> GridLayout(int rows, int columns, int horz, int vert) - It allows to specify the
horizontal and vertical space left between components with rows and columns.
■ Syntax:

setLayout(new GridLayout(3, 2));

Example:-

import java.awt.*;

import java.awt.event.*;
public class GridLayoutDemo extends Frame

int c=1;

static final int n=4;

public GridLayoutDemo() {

setSize(200, 200);

setVisible(true);

setLayout(new GridLayout(n, n));

setFont(new Font("Times New Roman", Font.BOLD, 24));

for(int i=0; i<n; i++)

for(int j=0; j<n; j++)

add(new Button(" "+c));

c++;

}
public static void main(String a[])

GridLayoutDemo gd=new GridLayoutDemo();

4. CardLayout:
■ It is unique among the other layout managers.
■ It manages the components in such a manner that only one component is visible at a time.
■ It treats each component as a card.
■ 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.
■ This can be useful for user interfaces with optional components that can be dynamically enabled and
disabled upon user input.
■ Constructors:
^ CardLayout() - it creates a layout with zero horizontal and vertical gap.
^ CardLayout(int hgap, vgap) - it creates a layout with the given horizontal and vertical gap.
■ Methods:-
^ void next(Container parent) - it is used to show the next card of the given container.
^ void previous(Container parent) - it is used to show the previous card of the given container.
^ void first(Container parent) - it is used to show the first card of the given container.
^ void last(Container parent) - it is used to show the last card of the given container.
^ void show(Container parent, String name) - it is used to display the card of the specified String name.
Example:-
import java.awt.*; import java.awt.event.*;

class CardLayoutDemo extends Frame implements ActionListener {


int index=1;
CardPanel p1, p2, p3;
CardLayout c;

Card LayoutDemo()
{
c=new CardLayout();

setSize(200, 200); setVisible(true);

setLayout(c);

p1=new CardPanel(this, "One"); p2=new CardPanel(this, "Two");


p3=new CardPanel(this, "Three");

add("First", p1); add("Second", p2); add("Third", p3);

c.show(this, "First");
}

public void actionPerformed(ActionEvent ae)


{
switch(++index)
{
case 1:
c.show(this, "First"); break;
case 2:
c.show(this, "Second"); break;
case 3:
c.show(this, "Third"); break;
}
if(index==3)
index=0;
}

public static void main(String arg[])


{
CardLayoutDemo cd=new CardLayoutDemo();
}
}

class CardPanel extends Panel {


Button b1;
Label 11;

CardPanel(CardLayoutDemo cd, String s)


{
b1=new Button("Next Card"); b1.addActionListener(cd);9:33 AM
7/12/2016 add(b1);

l1=new Label("This is card"+s); add(l1);


}
}

You might also like