0% found this document useful (0 votes)
5 views

AWT Tutorial (1)

Advance java programming 1st chapter important notes.

Uploaded by

harshchauhan0704
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

AWT Tutorial (1)

Advance java programming 1st chapter important notes.

Uploaded by

harshchauhan0704
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

AWT

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User


Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List, etc.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating
systems) subroutine for creating API components like TextField, ChechBox,
button, etc.
For example, an AWT GUI with components like TextField, label and button
will have different look and feel for the different platforms like Windows, MAC
OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates
those components.
In simple words, an AWT application will look like a windows application in
Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy

MADHAVI 1
AWT

Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
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.
Types of containers:
There are four types of containers in Java AWT:
 Window
 Panel
 Frame
 Dialog
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.

MADHAVI 2
AWT

Useful Methods of Component Class


Method Description
public void add(Component c) Inserts a component on this
component.
public void setSize(int width,int Sets the size (width and height) of the
height) component.
public void Defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean status) Changes the visibility of the
component, by default false.
Java AWT Button
A button is basically a control component with a label that generates an event
when pushed. The Button class is used to create a labeled button that has
platform independent implementation. The application result in some action
when the button is pushed.
When we press a button and release it, AWT sends an instance of ActionEvent
to that button by calling processEvent on the button. The processEvent method
of the button receives the all the events, then it passes an action event by calling
its own method processActionEvent. This method passes the action event on to
action listeners that are interested in the action events generated by the button.
To perform an action on a button being pressed and released, the ActionListener
interface needs to be implemented. The registered new listener can receive
events from the button by calling addActionListener method of the button. The
Java application can use the button's action command as a messaging protocol.
AWT Button Class Declaration
public class Button extends Component implements Accessible
Button Class Constructors
Constructor Description
Button( ) It constructs a new button with an empty string
i.e. it has no label.
Button (String text) It constructs a new button with given string as its
label.

MADHAVI 3
AWT

Button Class Methods


Method Description
void setText (String text) It sets the string message on the
button
String getText() It fetches the String message on the
button.
void setLabel (String label) It sets the label of button with the
specified string.
String getLabel() It fetches the label of the button.
void addNotify() It creates the peer of the button.
AccessibleContext It fetched the accessible context
getAccessibleContext() associated with the button.
void It adds the specified action listener to
addActionListener(ActionListener l) get the action events from the button.
String getActionCommand() It returns the command name of the
action event fired by the button.
ActionListener[ ] It returns an array of all the action
getActionListeners() listeners registered on the button.
T[ ] getListeners(Class listenerType) It returns an array of all the objects
currently registered as FooListeners
upon this Button.
protected String paramString() It returns the string which represents
the state of button.
protected void processActionEvent It process the action events on the
(ActionEvent e) button by dispatching them to a
registered ActionListener object.
protected void processEvent It process the events on the button
(AWTEvent e)
void removeActionListener It removes the specified action
(ActionListener l) listener so that it no longer receives
action events from the button.
void setActionCommand(String It sets the command name for the
command) action event given by the button.
Note: The Button class inherits methods from java.awt.Component and
java.lang.Object classes.
Java AWT Button Example 1
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

MADHAVI 4
AWT

// create instance of frame with the label


Frame f = new Frame("Button Example");
// create instance of button with label
Button b = new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,80,30);
// add button to the frame
f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Button Example 2
import java.awt.*;
import java.awt.event.*;
public class ButtonExample2
{
public static void main(String []args)
{
Frame f=new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50,170,20);
Button b=new Button("click here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener()

MADHAVI 5
AWT

{
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to ITTEAMWORK");
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Label
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.
AWT Label Class Declaration
public class Label extends Component implements Accessible
AWT Label Fields
The java.awt.Component class has following fields:
static int LEFT: It specifies that the label should be left justified.
static int RIGHT: It specifies that the label should be right justified.
static int CENTER: It specifies that the label should be placed in center.

MADHAVI 6
AWT

Label class Constructors


Constructor Description
Label() It constructs an empty label.
Label(String text) It constructs a label with the given string (left justified by
default).
Label(String text, It constructs a label with the specified string and the
int alignement) specified alignment.
Label Class Methods
Method Description
void setText(String text) It sets the texts for label with the
specified text.
void setAlignment(int alignment) It sets the alignment for label with the
specified alignment.
String getText() It gets the text of the label
int getAlignment() It gets the current alignment of the
label.
void addNotify() It creates the peer for the label.
AccessibleContext It gets the Accessible Context
getAccessibleContext() associated with the label.
protected String paramString() It returns the string the state of the
label.
Java AWT Label Example 1
import java.awt.*;
public class LabelEx
{
public static void main(String []args)
{
Frame f=new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label");
l2=new Label("Second Label");
l1.setBounds(50,100,100,30);
l2.setBounds(50,150,100,30);
f.add(l1);

MADHAVI 7
AWT

f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Label Example 2
import java.awt.*;
import java.awt.event.*;
public class LabelEx2 extends Frame implements ActionListener
{
TextField tf;
Label l;
Button b;
LabelEx2()
{
tf=new TextField();
tf.setBounds(50,50,150,20);
l=new Label();
l.setBounds(50,100,250,20);
b=new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);
add(l);
add(tf);
setSize(400,400);

MADHAVI 8
AWT

setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
String host=tf.getText();
String
ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public static void main(String []args)
{
new LabelEx2();
}
}
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key
typed), the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the
MADHAVI 9
AWT

ActionEvent is enabled on the text field, then the ActionEvent may be fired by
pressing return key. The event is handled by the ActionListener interface.
AWT TextField Class Declaration
public class TextField extends TextComponent
TextField Class constructors
Constructor Description
TextField() It constructs a new text field
component.
TextField(String text) It constructs a new text field
initialized with the given string text to
be displayed.
TextField(int columns) It constructs a new textfield (empty)
with given number of columns.
TextField(String text, int columns) It constructs a new text field with the
given text and given number of
columns (width).
TextField Class Methods
Method Description
void addNotify() It creates the peer of text field.
boolean echoCharIsSet() It tells whether text field has character
set for echoing or not.
void It adds the specified action listener to
addActionListener(ActionListener l) receive action events from the text
field.
ActionListener[] getActionListeners() It returns array of all action listeners
registered on text field.
AccessibleContext It fetches the accessible context
getAccessibleContext() related to the text field.
int getColumns() It fetches the number of columns in
text field.
char getEchoChar() It fetches the character that is used for
echoing.
Dimension getMinimumSize() It fetches the minimum dimensions
for the text field.
Dimension getMinimumSize(int It fetches the minimum dimensions
columns) for the text field with specified
number of columns.

1
MADHAVI
0
AWT

Dimension getPreferredSize() It fetches the preferred size of the text


field.
Dimension getPreferredSize(int It fetches the preferred size of the text
columns) field with specified number of
columns.
protected String paramString() It returns a string representing state of
the text field.
protected void It processes action events occurring in
processActionEvent(ActionEvent e) the text field by dispatching them to a
registered ActionListener object.
protected void It processes the event on text field.
processEvent(AWTEvent e)
void It removes specified action listener so
removeActionListener(ActionListener that it doesn't receive action events
l) anymore.
void setColumns(int columns) It sets the number of columns in text
field.
void setEchoChar(char c) It sets the echo character for text
field.
void setText(String t) It sets the text presented by this text
component to the specified text.
Java AWT TextField Example 1
import java.awt.*;
public class TextFieldEx
{
public static void main(String []args)
{
Frame f=new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Itteamwork");
t1.setBounds(50,100,200,30);
t2=new TextField("Awt Tutorial");
t2.setBounds(50,150,200,30);
f.add(t1);

1
MADHAVI
1
AWT

f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT TextField Example 2
import java.awt.*;
import java.awt.event.*;
public class TextFieldEx2 extends Frame implements ActionListener
{
TextField t1,t2,t3;
Button b1,b2;
TextFieldEx2()
{
t1=new TextField();
t1.setBounds(50,100,200,30);
t2=new TextField();
t2.setBounds(50,150,200,30);
t3=new TextField();
t3.setBounds(50,200,200,30);
t3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,250,50,50);
b2=new Button("-");
b2.setBounds(120,250,50,50);
b1.addActionListener(this);
1
MADHAVI
2
AWT

b2.addActionListener(this);
add(t1);
add(t2);
add(t3);
add(b1);
add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s1=t1.getText();
String s2=t2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1)
{
c=a+b;
}
else if(e.getSource()==b2)
{
c=a-b;
}
String result=String.valueOf(c);
t3.setText(result);
1
MADHAVI
3
AWT

}
public static void main(String []args)
{
new TextFieldEx2();
}}
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the
text area becomes larger than the viewable area, the scroll bar appears
automatically which helps us to scroll the text up and down, or right and left.
AWT TextArea Class Declaration
public class TextArea extends TextComponent
Fields of TextArea Class
The fields of java.awt.TextArea class are as follows:
static int SCROLLBARS_BOTH - It creates and displays both horizontal and
vertical scrollbars.
static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays
only the horizontal scrollbar.
static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only
the vertical scrollbar.
static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in
the text area.
Class constructors:
Constructor Description
TextArea() It constructs a new and empty text
area with no text in it.
TextArea (int row, int column) It constructs a new text area with
specified number of rows and
columns and empty string as text.

1
MADHAVI
4
AWT

TextArea (String text) It constructs a new text area and


displays the specified text in it.
TextArea (String text, int row, int It constructs a new text area with the
column) specified text in the text area and
specified number of rows and
columns.
TextArea (String text, int row, int It construcst a new text area with
column, int scrollbars) specified text in text area and
specified number of rows and
columns and visibility.
TextArea Class Methods
Method Description
void addNotify() It creates a peer of text area.
void append(String str) It appends the specified text to the
current text of text area.
AccessibleContext It returns the accessible context
getAccessibleContext() related to the text area
int getColumns() It returns the number of columns of
text area.
Dimension getMinimumSize() It determines the minimum size of a
text area.
Dimension getMinimumSize(int It determines the minimum size of a
rows, int columns) text area with the given number of
rows and columns.
Dimension getPreferredSize() It determines the preferred size of a
text area.
Dimension preferredSize(int rows, int It determines the preferred size of a
columns) text area with given number of rows
and columns.
int getRows() It returns the number of rows of text
area.
int getScrollbarVisibility() It returns an enumerated value that
indicates which scroll bars the text
area uses.
void insert(String str, int pos) It inserts the specified text at the
specified position in this text area.
protected String paramString() It returns a string representing the
state of this TextArea.
void replaceRange(String str, int start, It replaces text between the indicated
int end) start and end positions with the
specified replacement text.
1
MADHAVI
5
AWT

void setColumns(int columns) It sets the number of columns for this


text area.
void setRows(int rows) It sets the number of rows for this text
area.
Java AWT TextArea Example 1
import java.awt.*;
public class TextAreaEx
{
TextAreaEx()
{
Frame f=new Frame();
TextArea area=new TextArea("Welcome to Itteamwork");
area.setBounds(10,30,300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
{
new TextAreaEx();
}
}
Java AWT TextArea Example 2
import java.awt.*;
import java.awt.event.*;
public class TextAreaEx2 extends Frame implements ActionListener
{

1
MADHAVI
6
AWT

Label l1,l2;
TextArea area;
Button b;
TextAreaEx2()
{
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
area=new TextArea();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);
add(l2);
add(area);
add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
1
MADHAVI
7
AWT

l2.setText("Characters: "+text.length());
}
public static void main(String []args)
{
new TextAreaEx2();
}
}
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off"
or from "off" to "on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable,
Accessible
Checkbox Class Constructors
Constructor Description
Checkbox() It constructs a checkbox with no
string as the label.
Checkbox(String label) It constructs a checkbox with the
given label.
Checkbox(String label, boolean state) It constructs a checkbox with the
given label and sets the given state.
Checkbox(String label, boolean state, It constructs a checkbox with the
CheckboxGroup group) given label, set the given state in the
specified checkbox group.
Checkbox(String label, It constructs a checkbox with the
CheckboxGroup group, boolean state) given label, in the given checkbox
group and set to the specified state.
Checkbox Class Methods
Method name Description
void addItemListener(ItemListener It adds the given item listener to get
IL) the item events from the checkbox.
AccessibleContext It fetches the accessible context of
getAccessibleContext() checkbox.
1
MADHAVI
8
AWT

void addNotify() It creates the peer of checkbox.


CheckboxGroup It determines the group of checkbox.
getCheckboxGroup()
ItemListener[] getItemListeners() It returns an array of the item listeners
registered on checkbox.
String getLabel() It fetched the label of checkbox.
T[] getListeners(Class listenerType) It returns an array of all the objects
registered as FooListeners.
Object[] getSelectedObjects() It returns an array (size 1) containing
checkbox label and returns null if
checkbox is not selected.
boolean getState() It returns true if the checkbox is on,
else returns off.
protected String paramString() It returns a string representing the
state of checkbox.
protected void It processes the event on checkbox.
processEvent(AWTEvent e)
protected void It process the item events occurring in
processItemEvent(ItemEvent e) the checkbox by dispatching them to
registered ItemListener object.
void It removes the specified item listener
removeItemListener(ItemListener l) so that the item listener doesn't
receive item events from the
checkbox anymore.
void It sets the checkbox's group to the
setCheckboxGroup(CheckboxGroup given checkbox.
g)
void setLabel(String label) It sets the checkbox's label to the
string argument.
void setState(boolean state) It sets the state of checkbox to the
specified state.
Java AWT Checkbox Example 1
import java.awt.*;
public class CheckboxEx
{
CheckboxEx()
{
Frame f=new Frame("Checkbox Example");
1
MADHAVI
9
AWT

Checkbox cb1=new Checkbox("C++");


cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java",true);
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
{
new CheckboxEx();
}
}
Java AWT Checkbox Example 2
import java.awt.*;
import java.awt.event.*;
public class CheckboxEx2
{
CheckboxEx2()
{
Frame f=new Frame("Checkbox Example");
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
Checkbox cb1=new Checkbox("C++");
2
MADHAVI
0
AWT

cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java");
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.add(l);
cb1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
l.setText("C++ Checkbox:
"+(e.getStateChange()==1?"checked":"unchecked"));
}
});
cb2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
l.setText("Java Checkbox:
"+(e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)

2
MADHAVI
1
AWT

{
new CheckboxEx2();
}
}
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox.
At a time only one check box button is allowed to be in "on" state and
remaining check box button in "off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no
special control for creating radio buttons in AWT.
AWT CheckboxGroup Class Declaration
public class CheckboxGroup extends Object implements Serializable
Java AWT CheckboxGroup Example1
import java.awt.*;
public class CheckboxGroupEx
{
CheckboxGroupEx()
{
Frame f=new Frame("CheckboxGroup Example");
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("C++",cbg,false);
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java",cbg,false);
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.setSize(400,400);
f.setLayout(null);
2
MADHAVI
2
AWT

f.setVisible(true);
}
public static void main(String []args)
{
new CheckboxGroupEx();
}
}
Java AWT CheckboxGroup Example 2
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupEx2
{
CheckboxGroupEx2()
{
Frame f=new Frame("CheckboxGroup Example");
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("C++",cbg,false);
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java",cbg,false);
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.add(l);
cb1.addItemListener(new ItemListener()
2
MADHAVI
3
AWT

{
public void itemStateChanged(ItemEvent e)
{
l.setText("C++ Checkbox: checked");
}
});
cb2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
l.setText("Java Checkbox: checked");
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
{
new CheckboxGroupEx2();
}
}
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
public class Choice extends Component implements ItemSelectable, Accessible

2
MADHAVI
4
AWT

Choice Class constructor


Constructor Description
Choice() It constructs a new choice menu.
Choice Class Methods
Method name Description
void add(String item) It adds an item to the choice menu.
void addItemListener(ItemListener l) It adds the item listener that receives
item events from the choice menu.
void addNotify() It creates the peer of choice.
AccessibleContext It gets the accessbile context related
getAccessibleContext() to the choice.
String getItem(int index) It gets the item (string) at the given
index position in the choice menu.
int getItemCount() It returns the number of items of the
choice menu.
ItemListener[] getItemListeners() It returns an array of all item listeners
registered on choice.
T[] getListeners(Class listenerType) Returns an array of all the objects
currently registered as FooListeners
upon this Choice.
int getSelectedIndex() Returns the index of the currently
selected item.
String getSelectedItem() Gets a representation of the current
choice as a string.
Object[] getSelectedObjects() Returns an array (length 1) containing
the currently selected item.
void insert(String item, int index) Inserts the item into this choice at the
specified position.
protected String paramString() Returns a string representing the state
of this Choice menu.
protected void It processes the event on the choice.
processEvent(AWTEvent e)
protected void processItemEvent Processes item events occurring on
(ItemEvent e) this Choice menu by dispatching
them to any registered ItemListener
objects.
void remove(int position) It removes an item from the choice
menu at the given index position.
void remove(String item) It removes the first occurrence of the
item from choice menu.
2
MADHAVI
5
AWT

void removeAll() It removes all the items from the


choice menu.
void removeItemListener It removes the mentioned item
(ItemListener l) listener. Thus is doesn't receive item
events from the choice menu
anymore.
void select(int pos) It changes / sets the selected item in
the choice menu to the item at given
index position.
void select(String str) It changes / sets the selected item in
the choice menu to the item whose
string value is equal to string
specified in the argument.
Java AWT Choice Example1
import java.awt.*;
public class ChoiceEx
{
ChoiceEx()
{
Frame f= new Frame("Choice Example");
Choice c=new Choice();
c.setBounds(100,100,75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);

2
MADHAVI
6
AWT

}
public static void main(String []args)
{
new ChoiceEx();
}
}
Java AWT Choice Example2
import java.awt.*;
import java.awt.event.*;
public class ChoiceEx2 extends Frame
{
ChoiceEx2()
{
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
Button b=new Button("Show");
b.setBounds(200,100,50,20);
final Choice c=new Choice();
c.setBounds(100,100,75,75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
add(c);
add(l);
2
MADHAVI
7
AWT

add(b);
setSize(500,500);
setLayout(null);
setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data="Programming Language Selected:
"+c.getItem(c.getSelectedIndex());
l.setText(data);
}
});
}
public static void main(String []args)
{
new ChoiceEx2();
}
}
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible

2
MADHAVI
8
AWT

AWT List Class Constructors


Constructor Description
List() It constructs a new scrolling list.
List(int row_num) It constructs a new scrolling list
initialized with the given number of
rows visible.
List(int row_num, Boolean It constructs a new scrolling list
multipleMode) initialized which displays the given
number of rows.
List Class Methods
Method name Description
void add(String item) It adds the specified item into the end
of scrolling list.
void add(String item, int index) It adds the specified item into list at
the given index position.
void It adds the specified action listener to
addActionListener(ActionListener l) receive action events from list.
void addItemListener(ItemListener l) It adds specified item listener to
receive item events from list.
void addNotify() It creates peer of list.
void deselect(int index) It deselects the item at given index
position.
AccessibleContext It fetches the accessible context
getAccessibleContext() related to the list.
ActionListener[] getActionListeners() It returns an array of action listeners
registered on the list.
String getItem(int index) It fetches the item related to given
index position.
int getItemCount() It gets the count/number of items in
the list.
ItemListener[] getItemListeners() It returns an array of item listeners
registered on the list.
String[] getItems() It fetched the items from the list.
Dimension getMinimumSize() It gets the minimum size of a
scrolling list.
Dimension getMinimumSize(int It gets the minimum size of a list with
rows) given number of rows.
Dimension getPreferredSize() It gets the preferred size of list.
Dimension getPreferredSize(int rows) It gets the preferred size of list with
given number of rows.
2
MADHAVI
9
AWT

int getRows() It fetches the count of visible rows in


the list.
int getSelectedIndex() It fetches the index of selected item of
list.
int[] getSelectedIndexes() It gets the selected indices of the list.
String getSelectedItem() It gets the selected item on the list.
String[] getSelectedItems() It gets the selected items on the list.
Object[] getSelectedObjects() It gets the selected items on scrolling
list in array of objects.
int getVisibleIndex() It gets the index of an item which was
made visible by method
makeVisible()
void makeVisible(int index) It makes the item at given index
visible.
boolean isIndexSelected(int index) It returns true if given item in the list
is selected.
boolean isMultipleMode() It returns the true if list allows
multiple selections.
protected String paramString() It returns parameter string
representing state of the scrolling list.
protected void It process the action events occurring
processActionEvent(ActionEvent e) on list by dispatching them to a
registered ActionListener object.
protected void It process the events on scrolling list.
processEvent(AWTEvent e)
protected void It process the item events occurring
processItemEvent(ItemEvent e) on list by dispatching them to a
registered ItemListener object.
void It removes specified action listener.
removeActionListener(ActionListener Thus it doesn't receive further action
l) events from the list.
void It removes specified item listener.
removeItemListener(ItemListener l) Thus it doesn't receive further action
events from the list.
void remove(int position) It removes the item at given index
position from the list.
void remove(String item) It removes the first occurrence of an
item from list.
void removeAll() It removes all the items from the list.
void replaceItem(String newVal, int It replaces the item at the given index
index) in list with the new string specified.

3
MADHAVI
0
AWT

void select(int index) It selects the item at given index in


the list.
void setMultipleMode(boolean b) It sets the flag which determines
whether the list will allow multiple
selection or not.
void removeNotify() It removes the peer of list.
Java AWT List Example 1
import java.awt.*;
public class ListEx extends Frame
{
ListEx()
{
List l1=new List(5);
l1.setBounds(100,100,75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
add(l1);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String []args)
{
new ListEx();
}
}
3
MADHAVI
1
AWT

Java AWT List Example 2


import java.awt.*;
import java.awt.event.*;
public class ListEx2 extends Frame
{
ListEx2()
{
final Label label=new Label();
label.setAlignment(Label.CENTER);
label.setSize(500,100);
Button b=new Button("Show");
b.setBounds(200,150,80,30);
final List l1=new List(4,false);
l1.setBounds(100,100,70,70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4,false);
l2.setBounds(100,200,70,70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("Codelgniter");
add(label);
add(b);
add(l1);
3
MADHAVI
2
AWT

add(l2);
setSize(450,450);
setLayout(null);
setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data="Programming Language Selected:
"+l1.getItem(l1.getSelectedIndex());
data +=" ,FrameworkSelected: ";
for(String frame:l2.getSelectedItems())
{
data+=frame +"";
}
label.setText(data);
}
});
}
public static void main(String []args)
{
new ListEx2();
}
}
Java AWT Canvas
The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits the
Component class.
3
MADHAVI
3
AWT

AWT Canvas class Declaration


public class Canvas extends Component implements Accessible
Canvas Class Constructors
Constructor Description
Canvas() It constructs a new Canvas.
Canvas(GraphicConfiguration config) It constructs a new Canvas with the
given Graphic Configuration object.
Class methods
Method name Description
void addNotify() It creates the canvas's peer.
void createBufferStrategy (int It creates a new multi buffering
numBuffers) strategies on the particular
component.
void createBufferStrategy (int It creates a new multi buffering
numBuffers, BufferCapabilities caps) strategies on the particular component
with the given buffer capabilities.
AccessibleContext It gets the accessible context related
getAccessibleContext() to the Canvas.
BufferStrategy getBufferStrategy() It returns the buffer strategy used by
the particular component.
void paint(Graphics g) It paints the canvas with given
Graphics object.
void pdate(Graphics g) It updates the canvas with given
Graphics object.
Java AWT Canvas Example 1
import java.awt.*;
public class CanvasExample
{
public CanvasExample()
{
Frame f = new Frame("Canvas Example");
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
3
MADHAVI
4
AWT

f.setVisible(true);
}
public static void main(String args[])
{
new CanvasExample();
}
}
class MyCanvas extends Canvas
{
public MyCanvas() {
setBackground (Color.cyan);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
AWT Scrollbar Class Declaration
public class Scrollbar extends Component implements Adjustable, Accessible

3
MADHAVI
5
AWT

Scrollbar Class Fields


The fields of java.awt.Image class are as follows:
static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.
static int VERTICAL - It is a constant to indicate a vertical scroll bar.
Scrollbar Class Constructors
Constructor Description
Scrollbar() Constructs a new vertical scroll bar.
Scrollbar(int orientation) Constructs a new scroll bar with the
specified orientation.
Scrollbar(int orientation, int value, int Constructs a new scroll bar with the
visible, int minimum, int maximum) specified orientation, initial value,
visible amount, and minimum and
maximum values.
Scrollbar Class Methods
Method name Description
void addAdjustmentListener It adds the given adjustment listener
(AdjustmentListener l) to receive instances of
AdjustmentEvent from the scroll bar.
void addNotify() It creates the peer of scroll bar.
int getBlockIncrement() It gets the block increment of the
scroll bar.
int getMaximum() It gets the maximum value of the
scroll bar.
int getMinimum() It gets the minimum value of the
scroll bar.
int getOrientation() It returns the orientation of scroll bar.
int getUnitIncrement() It fetches the unit increment of the
scroll bar.
int getValue() It fetches the current value of scroll
bar.
int getVisibleAmount() It fetches the visible amount of scroll
bar.
boolean getValueIsAdjusting() It returns true if the value is in
process of changing where action
results are being taken by the user.
protected String paramString() It returns a string representing the
state of Scroll bar.

3
MADHAVI
6
AWT

protected void It processes the adjustment event


processAdjustmentEvent occurring on scroll bar by dispatching
(AdjustmentEvent e) them to any registered
AdjustmentListener objects.
protected void It processes the events on the scroll
processEvent(AWTEvent e) bar.
void removeAdjustmentListener It removes the given adjustment
(AdjustmentListener l) listener. Thus it no longer receives the
instances of AdjustmentEvent from
the scroll bar.
void setBlockIncrement(int v) It sets the block increment from scroll
bar.
void setMaximum (int It sets the maximum value of the
newMaximum) scroll bar.
void setMinimum (int newMinimum) It sets the minimum value of the
scroll bar.
void setOrientation (int orientation) It sets the orientation for the scroll
bar.
void setUnitIncrement(int v) It sets the unit increment for the scroll
bar.
void setValue (int newValue) It sets the value of scroll bar with the
given argument value.
void setValueIsAdjusting (boolean b) It sets the valueIsAdjusting property
to scroll bar.
void setValues (int value, int visible, It sets the values of four properties for
int minimum, int maximum) scroll bar: value, visible amount,
minimum and maximum.
void setVisibleAmount (int It sets the visible amount of the scroll
newAmount) bar.
AccessibleContext It gets the accessible context related
getAccessibleContext() to the scroll bar.
AdjustmentListener[] It returns an array of al lthe
getAdjustmentListeners() adjustment listeners registered on the
scroll bar.
T[] getListeners(Class listenerType) It returns an array if all objects that
are registered as FooListeners on the
scroll bar currently.
Java AWT Scrollbar Example 1
import java.awt.*;
public class ScrollbarEx extends Frame

3
MADHAVI
7
AWT

{
ScrollbarEx()
{
Scrollbar s=new Scrollbar();
s.setBounds(100,100,50,100);
add(s);
setSize(500,500);
setLayout(null);
setVisible(true);
}
public static void main(String []args)
{
new ScrollbarEx();
}
}
Java AWT Scrollbar Example 2
import java.awt.*;
import java.awt.event.*;
public class ScrollbarEx2 extends Frame
{
ScrollbarEx2()
{
final Label l=new Label();
l.setAlignment(Label.CENTER);
l.setSize(400,100);
final Scrollbar s=new Scrollbar();
s.setBounds(100,100,50,100);
3
MADHAVI
8
AWT

add(s);
add(l);
setSize(500,500);
setLayout(null);
setVisible(true);
s.addAdjustmentListener(new AdjustmentListener(){
public void adjustmentValueChanged(AdjustmentEvent e)
{
l.setText("Vertical Scrollbar value is: "+s.getValue());
}
});
}
public static void main(String []args)
{
new ScrollbarEx2();
}
}
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.
AWT MenuItem class declaration
public class MenuItem extends MenuComponent implements Accessible
Java AWT MenuItem and Menu Example
import java.awt.*;
class MenuExample

3
MADHAVI
9
AWT

{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
4
MADHAVI
0
AWT

}
Java AWT PopupMenu
PopupMenu can be dynamically popped up at specific position within a
component. It inherits the Menu class.
Example:
import java.awt.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final Frame f= new Frame("PopupMenu Example");
final PopupMenu popupmenu = new PopupMenu("Edit");
MenuItem cut = new MenuItem("Cut");
cut.setActionCommand("Cut");
MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);

4
MADHAVI
1
AWT

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}
}
Java AWT Panel
The Panel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the Container class.
It doesn't have title bar.
Example:
import java.awt.*;
public class PanelExample
{
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.cyan);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.pink);
Button b2=new Button("Button 2");

4
MADHAVI
2
AWT

b2.setBounds(100,100,80,30);
b2.setBackground(Color.blue);
panel.add(b1);
panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used
to take some form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and
minimize buttons but Dialog doesn't have.
Example:
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static Dialog d;

4
MADHAVI
3
AWT

DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Java AWT Toolkit
Toolkit class is the abstract superclass of every implementation in the Abstract
Window Toolkit. Subclasses of Toolkit are used to bind various components. It
inherits Object class.

4
MADHAVI
4
AWT

Example1:
import java.awt.*;
public class ToolkitExample
{
public static void main(String[] args)
{
Toolkit t = Toolkit.getDefaultToolkit();
System.out.println("Screen resolution = " + t.getScreenResolution());
Dimension d = t.getScreenSize();
System.out.println("Screen width = " + d.width);
System.out.println("Screen height = " + d.height);
}
}
Example 2: Beep()
import java.awt.*;
import java.awt.event.*;
public class ToolkitExample2
{
public static void main(String[] args)
{
Frame f=new Frame("ToolkitExample2");
Button b=new Button("beep");
b.setBounds(50,100,60,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
4
MADHAVI
5
AWT

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Toolkit.getDefaultToolkit().beep();
}
});
}
}
Example 3:Icon Image
import java.awt.*;
class ToolkitExample3
{
ToolkitExample3()
{
Frame f=new Frame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.jpg");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[])
{
new ToolkitExample3();
}
}

4
MADHAVI
6
AWT

Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on
the registered component.
public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement
the ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here
}
Java ActionListener Example: On Button click
import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample
{
public static void main(String []args)
{
Frame f=new Frame("ActionListener Example");
final TextField t=new TextField();

4
MADHAVI
7
AWT

t.setBounds(50,50,150,20);
Button b=new Button("Chick Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
t.setText("Welcome to Itteamwork.");
}
});
f.add(b);
f.add(t);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It
is notified against MouseEvent. The MouseListener interface is found in
java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);

4
MADHAVI
8
AWT

MouseListenerExample1 in AWT.
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
4
MADHAVI
9
AWT

public void mouseReleased(MouseEvent e) {


l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
MouseListenerExample2 in AWT.
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements
MouseListener
{
MouseListenerExample2()
{
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}

5
MADHAVI
0
AWT

public void mouseEntered(MouseEvent e) {}


public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args)
{
new MouseListenerExample2();
}
}
Java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse.
It is notified against MouseEvent. The MouseMotionListener interface is found
in java.awt.event package. It has two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in MouseMotionListener interface are given
below:
public abstract void mouseDragged(MouseEvent e);
public abstract void mouseMoved(MouseEvent e);
MouseMotionListenerExample in AWT.
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener
{
Label l;
Color c=Color.BLUE;
MouseMotionListenerExample()
{

5
MADHAVI
1
AWT

l=new Label();
l.setBounds(20,40,100,20);
add(l);
addMouseMotionListener(this);
setSize(500,500);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
l.setText("X="+e.getX()+",Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e)
{
l.setText("X="+e.getX()+",Y="+e.getY());
}
public static void main(String[] args)
{
new MouseMotionListenerExample();
}
}

5
MADHAVI
2
AWT

Java ItemListener Interface


The Java ItemListener is notified whenever you click on the checkbox.It is
notified against ItemEvent. The ItemListener interface is found in
java.awt.event package.
It has only one method: itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click
or unclick on the registered checkbox component.
public abstract void itemStateChanged(ItemEvent e);
ItemListenerExample in AWT.
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample()
{
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
5
MADHAVI
3
AWT

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "+
(e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "+
(e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is
notified against KeyEvent. The KeyListener interface is found in java.awt.event
package, and it has three methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
public interface KeyListener extends EventListener

5
MADHAVI
4
AWT

Methods of KeyListener interface


Method name Description
public abstract void keyPressed It is invoked when a key has been
(KeyEvent e); pressed.
public abstract void keyReleased It is invoked when a key has been
(KeyEvent e); released.
public abstract void keyTyped It is invoked when a key has been
(KeyEvent e); typed.
Methods inherited
This interface inherits methods from the following interface:
java.awt.EventListener
KeyListenerExample in AWT.
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l = new Label();
l.setBounds (20, 50, 300, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);

5
MADHAVI
5
AWT

setVisible (true);
}
public void keyPressed (KeyEvent e)
{
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e)
{
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters: "+text.length());
}
public void keyTyped (KeyEvent e)
{
l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
KeyListenerExample 2 (Count Words & Characters)
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample2 extends Frame implements KeyListener {
// object of Label and TextArea
5
MADHAVI
6
AWT

Label l;
TextArea area;
// class constructor
KeyListenerExample2() {
// creating the label
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to the text area
area.addKeyListener(this);
// adding label and text area to frame
add(l);
add(area);
// setting size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// even if we do not define the interface methods, we need to override them
public void keyPressed(KeyEvent e) {}
// overriding the keyReleased() method of KeyListener interface
public void keyReleased (KeyEvent e) {
// defining a string which is fetched by the getText() method of TextArea class
5
MADHAVI
7
AWT

String text = area.getText();


// splitting the string in words
String words[] = text.split ("\\s");
// printing the number of words and characters of the string
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
public void keyTyped(KeyEvent e) {}
// main method
public static void main(String[] args) {
new KeyListenerExample2();
}
}
Java WindowListener Interface
The Java WindowListener is notified whenever you change the state of window.
It is notified against WindowEvent. The WindowListener interface is found in
java.awt.event package. It has three methods.
WindowListener interface declaration
The declaration for java.awt.event.WindowListener interface is shown below:
public interface WindowListener extends EventListener
Methods of WindowListener interface
Method signature Description
public abstract void windowActivated It is called when the Window is set to
(WindowEvent e) be an active Window.
public abstract void windowClosed It is called when a window has been
(WindowEvent e) closed as the result of calling dispose
on the window.
public abstract void windowClosing It is called when the user attempts to
(WindowEvent e) close the window from the system
menu of the window.

5
MADHAVI
8
AWT

public abstract void It is called when a Window is not an


windowDeactivated (WindowEvent active Window anymore.
e)
public abstract void It is called when a window is changed
windowDeiconified (WindowEvent from a minimized to a normal state.
e)
public abstract void windowIconified It is called when a window is changed
(WindowEvent e) from a normal to a minimized state.
public abstract void windowOpened It is called when window is made
(WindowEvent e) visible for the first time.
Working of WindowListener interface
 If a class needs to process some Window events, an object should exist
which can implement the interface.
 As the object is already registered with Listener, an event will be
generated on all the states of window.
 This helps in generation of invocation of relevant method in listener's
object. And then WindowEvent is passed after invocation.
WindowExample
import java.awt.*;
import java.awt.event.*;
public class WindowExample extends Frame implements WindowListener
{
WindowExample()
{
addWindowListener(this);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public static void main(String[] args)
{
new WindowExample();
5
MADHAVI
9
AWT

}
public void windowActivated (WindowEvent arg0)
{
System.out.println("activated");
}
public void windowClosed (WindowEvent arg0)
{
System.out.println("closed");
}
public void windowClosing (WindowEvent arg0)
{
System.out.println("closing");
dispose();
}
public void windowDeactivated (WindowEvent arg0)
{
System.out.println("deactivated");
}
public void windowDeiconified (WindowEvent arg0)
{
System.out.println("deiconified");
}
public void windowIconified (WindowEvent arg0)
{
System.out.println("iconified");
}
public void windowOpened (WindowEvent arg0)
6
MADHAVI
0
AWT

{
System.out.println("opened");
}
}
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. 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.
Pros of using Adapter classes:
 It assists the unrelated classes to work combinedly.
 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and
javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given
below.
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
java.awt.dnd Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

6
MADHAVI
1
AWT

javax.swing.event Adapter classes


Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Java WindowAdapter Example
In the following example, we are implementing the WindowAdapter class of
AWT and one its methods windowClosing() to close the frame window.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
public class AdapterExample {
// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
}
});
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);

6
MADHAVI
2
AWT

}
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Java MouseAdapter Example
In the following example, we are implementing the MouseAdapter class. The
MouseListener interface is added into the frame to listen the mouse event in the
frame.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseAdapter class
public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);

6
MADHAVI
3
AWT

}
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using
getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Java MouseMotionAdapter Example
In the following example, we are implementing the MouseMotionAdapter class
and its different methods to listen to the mouse motion events in the Frame
window.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
6
MADHAVI
4
AWT

MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using
getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
Java KeyAdapter Example
In the following example, we are implementing the KeyAdapter class and its
method.

6
MADHAVI
5
AWT

// importing the necessary libraries


import java.awt.*;
import java.awt.event.*;
// class which inherits the KeyAdapter class
public class KeyAdapterExample extends KeyAdapter {
// creating objects of Label, TextArea and Frame
Label l;
TextArea area;
Frame f;
// class constructor
KeyAdapterExample() {
// creating the Frame with title
f = new Frame ("Key Adapter");
// creating the Label
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to text area
area.addKeyListener(this);
// adding the label and text area to frame
f.add(l);
f.add(area);
// setting the size, layout and visibility of frame
6
MADHAVI
6
AWT

f.setSize (400, 400);


f.setLayout (null);
f.setVisible (true);
}
// overriding the keyReleased() method
public void keyReleased (KeyEvent e) {
// creating the String object to get the text fromTextArea
String text = area.getText();
// splitting the String into words
String words[] = text.split ("\\s");
// setting the label text to print the number of words and characters of given
string
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
// main method
public static void main(String[] args) {
new KeyAdapterExample();
}
}
How to close AWT Window in Java
We can close the AWT Window or Frame by calling dispose() or System.exit()
inside windowClosing() method. The windowClosing() method is found in
WindowListener interface and WindowAdapter class.
The WindowAdapter class implements WindowListener interfaces. It provides
the default implementation of all the 7 methods of WindowListener interface.
To override the windowClosing() method, you can either use WindowAdapter
class or WindowListener interface.

6
MADHAVI
7
AWT

If you implement the WindowListener interface, you will be forced to override


all the 7 methods of WindowListener interface. So it is better to use
WindowAdapter class.
Different ways to override windowClosing() method
 By anonymous class
 By inheriting WindowAdapter class
 By implementing WindowListener interface
Close AWT Window Example 1: Anonymous class
In the following example, we are implementing the windowClosing() method of
Window using the Anonymous class
// importing necessary awt libraries
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
// class which inherits the Frame class
public class WindowExample extends Frame {
// class constructor
WindowExample() {
// adding WindowListener to the Frame
// and using the windowClosing() method of WindowAdapter class
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
dispose();
}
});
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);

6
MADHAVI
8
AWT

setVisible (true);
}
// main method
public static void main (String[] args) {
new WindowExample();
}
Close AWT Window Example 2: extending WindowAdapter
In the following example, we are implementing the window closing
functionality using the WindowAdapter class.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the WindowAdapter class
public class AdapterExample extends WindowAdapter {
// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating the frame
f = new Frame();
// adding WindowListener to the frame
f.addWindowListener (this);
// setting the size, layout and visibility of frame
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}

6
MADHAVI
9
AWT

// overriding the windowClosing() method


public void windowClosing (WindowEvent e) {
f.dispose();
}
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Close AWT Window Example 3: implementing WindowListener
In the following example, we are implementing the WindowListener interface
to display the functionality of closing the AWT Window.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
// class which inherits Frame class and implement the WindowListener interface
public class WindowExample extends Frame implements WindowListener {
// constructor
WindowExample() {
// adding WindowListener to frame
addWindowListener(this);
// setting the size, layout and visibility of frame
setSize(400,400);
setLayout(null);
setVisible(true);
}

7
MADHAVI
0
AWT

// main method
public static void main(String[] args) {
new WindowExample();
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
dispose();
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent arg0) {}
}

7
MADHAVI
1

You might also like