Chapter 2: Working With Frames AWT Controls and Events

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

BCA III Yr.

V SEM Advance JAVA


Chapter 2: Working with Frames AWT controls and Events

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


applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


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.
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.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

1
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Frame Class
The Frame class is a top level window. The type of window is defined by Frame. It has border
and title. Frame() constructor is used to create Frame window.
Declaration of Frame Class

public class Frame


extends Windwo
implements MenuCountainer

Useful Methods of Component class

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
1) By extending Frame class (inheritance)
2) By creating the object of Frame class (association)

By extending Frame class (inheritance)


AWT Example by Inheritance
import java.awt.*;
class firstawt extends Frame
{
firstawt() {
Button b = new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
2
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

public static void main(String args[])


{
firstawt a =new firstawt();
}
}

By creating the object of Frame class (association)

AWT Example by creating object of the Frame class


import java.awt.*;
public class SecondAwt
{
SecondAwt()
{ //Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
fr.add(lb);
//Creating Text Field
TextField t = new TextField();
fr.add(t);
fr.setSize(500, 300);
//Setting the layout for the Frame
fr.setLayout(newFlowLayout());
fr.setVisible(true);
}
public static void main(String args[])
{
SecondAwt ex = new SecondAwt();
}
}

3
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Layout Manager
The Layout managers enable us to control the way in which visual components are arranged in
the GUI forms by determining the size and position of components within the containers.
LayoutManager is an interface that is implemented by all the classes of layout managers.
There are following classes that represent the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout

BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Example:
import java.awt.*;
public class Border
{
Frame f;
Border()
{
f = new Frame();
Button b1 = new Button("NORTH");
Button b2 = new Button("SOUTH");
Button b3 = new Button("EAST");
Button b4 = new Button("WEST");
Button b5 = new Button("CENTER");

4
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
new Border();
}
}

Flow Layout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Example:
import java.lang.*;
import java.awt.*;
public class Flow
{
Frame f;
Flow()
{
f = new Frame();
Button b1 = new Button("1");
Button b2 = new Button("2");
5
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Button b3 = new Button("3");


Button b4 = new Button("4");
Button b5 = new Button("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new
FlowLayout(FlowLayout.CENTER));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
new Flow();
}
}

Grid Layout
It arranges all the components in a grid of equally sized cells, adding them from the left to right
and top to bottom. Only one component can be placed in a cell and each region of the grid will
have the same size. When the container is resized, all cells are automatically resized. The order
of placing the components in a cell is determined as they were added.
import java.awt.*;
import java.lang.*;
import java.awt.*;
public class MyGrid
{
Frame f;
MyGrid()
{
f = new Frame();
Button b1 = new Button("1");
Button b2 = new Button("2");
6
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Button b3 = new Button("3");


Button b4 = new Button("4");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.setLayout(new GridLayout(2,2));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
new MyGrid();
}
}

Card Layout
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
Commonly used methods of CardLayout class
public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with the
given name.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.*;
class Cardlayout extends JFrame implements ActionListener {
CardLayout card;
JButton b1, b2, b3;
Container c;
7
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Cardlayout()
{
c = getContentPane();
card = new CardLayout(40, 30);
c.setLayout(card);
b1 = new JButton("ITM");
b2 = new JButton("NANDED");
b3 = new JButton("BCAIII");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a", b1); c.add("b", b2); c.add("c", b3);
}
public void actionPerformed(ActionEvent e)
{

// call the next card


card.next(c);
}

// Main Method
public static void main(String[] args)
{

// Creating Object of CardLayout class.


Cardlayout cl = new Cardlayout();

// Function to set size of JFrame.


cl.setSize(400, 400);

// Function to set visibility of JFrame.


cl.setVisible(true);

// Function to set default operation of JFrame.


8
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Box Layout
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants.
Fields of BoxLayout class:

public static final int X_AXIS


public static final int Y_AXIS
public static final int LINE_AXIS
public static final int PAGE_AXIS
Note: BoxLayout class is found in javax.swing package.
import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample2 extends Frame {
Button buttons[];
public BoxLayoutExample2() {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample2 b=new BoxLayoutExample2();
} }
import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame {
9
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

GridBag Layout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the help of constraints
object we arrange component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine component's size.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
10
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

GridBagConstraints gbc = new GridBagConstraints();


setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}}
AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.
Sr. Control & Description

11
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

No.

1 Label
A Label object is a component for placing text in a container.
2 Button
This class creates a labeled button.
3 Check Box
A check box is a graphical component that can be in either an on (true) or off (false)
state.
4 Check Box Group
The CheckboxGroup class is used to group the set of checkbox.
5 List
The List component presents the user with a scrolling list of text items.
6 Text Field
A TextField object is a text component that allows for the editing of a single line of text.
7 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.
8 Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.
9 Canvas
A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
10 Image
An Image control is superclass for all image classes representing graphical images.
11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.

12
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

12 Dialog
A Dialog control represents a top-level window with a title and a border used to take
some form of input from the user.
13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.

AWT Button Class


Introduction
Button is a control component that has a label and generates an event when pressed. When a
button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling
processEvent on the button. The button's processEvent method receives all events for the
button; it passes an action event along by calling its own processActionEvent method. The latter
method passes the action event on to any action listeners that have registered an interest in
action events generated by this button.
If an application wants to perform some action based on a button being pressed and released, it
should implement ActionListener and register the new listener to receive events from this
button, by calling the button's addActionListener method. The application can make use of the
button's action command as a messaging protocol.
Class declaration
Following is the declaration for java.awt.Button class:
public class Button
extends Component
implements Accessible
Class constructors
S.N. Constructor & Description

1 Button()
Constructs a button with an empty string for its label.
2 Button(String text)
Constructs a new button with specified label.

Class methods
S.N. Method & Description

1 void addActionListener(ActionListener l)

13
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Adds the specified action listener to receive action events from this button.
2 void addNotify()
Creates the peer of the button.
3 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Button.
4 String getActionCommand()
Returns the command name of the action event fired by this button.
5 ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this button.
6 String getLabel()
Gets the label of this button.
7 <T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Button.
8 protected String paramString()
Returns a string representing the state of this Button.
9 protected void processActionEvent(ActionEvent e)
Processes action events occurring on this button by dispatching them to any registered
ActionListener objects.
10 protected void processEvent(AWTEvent e)
Processes events on this button.
11
void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from this
button.
12 void setActionCommand(String command)
Sets the command name for the action event fired by this button.
13 void setLabel(String label)
Sets the button's label to be the specified string.

14
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

AWT Label Class


Introduction
Label is a passive control because it does not create any event when accessed by the user. The
label control is an object of Label. A label displays a single line of read-only text. However the
text can be changed by the application programmer but cannot be changed by the end user in
any way.
Class declaration
Following is the declaration for java.awt.Label class:
public class Label
extends Component
implements Accessible
Field
Following are the fields for java.awt.Component class:
• static int CENTER -- Indicates that the label should be centered.
• static int LEFT -- Indicates that the label should be left justified.
• static int RIGHT -- Indicates that the label should be right justified.
Class constructors
S.N. Constructor & Description

1 Label()
Constructs an empty label.
2 Label(String text)
Constructs a new label with the specified string of text, left justified.
3 Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the specified
alignment.

Class methods
S.N. Method & Description

15
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

1 void addNotify()
Creates the peer for this label.
2 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Label.
3 int getAlignment()
Gets the current alignment of this label.
4 String getText()
Gets the text of this label.
5 protected String paramString()
Returns a string representing the state of this Label.
6 void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment.
7 void setText(String text)
Sets the text for this label to the specified text.

AWT CheckBox Class


Introduction
Checkbox control is used to turn an option on(true) or off(false). There is label for each
checkbox representing what the checkbox does.The state of a checkbox can be changed by
clicking on it.
Class declaration
Following is the declaration for java.awt.Checkbox class:
public class Checkbox
extends Component
implements ItemSelectable,Accessible

Class constructors
S.N. Constructor & Description

16
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

1 Checkbox()
Creates a check box with an empty string for its label.
2 Checkbox(String label)
Creates a check box with the specified label.
3 Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.
4 Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified state, and in the
specified check box group.
5 Checkbox(String label, CheckboxGroup group, boolean state)
Creates a check box with the specified label, in the specified check box group, and set to
the specified state.

Class methods
S.N. Method & Description

1 void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box.
2 void addNotify()
Creates the peer of the Checkbox.
3 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Checkbox.
4 CheckboxGroup getCheckboxGroup()
Determines this check box's group.
5 ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this checkbox.
6 String getLabel()
Gets the label of this check box.

17
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

7 <T extends EventListener>T[] getListeners(Class<T> listenerType)


Returns an array of all the objects currently registered as FooListeners upon this
Checkbox.
8 Object[] getSelectedObjects()
Returns an array (length 1) containing the checkbox label or null if the checkbox is not
selected.
9 boolean getState()
Determines whether this check box is in the on or off state.
10 protected String paramString()
Returns a string representing the state of this Checkbox.
11 protected void processEvent(AWTEvent e)
Processes events on this check box.
12 protected void processItemEvent(ItemEvent e)
Processes item events occurring on this check box by dispatching them to any registered
ItemListener objects.
13 void removeItemListener(ItemListener l)
Removes the specified item listener so that the item listener no longer receives item
events from this check box.
14 void setCheckboxGroup(CheckboxGroup g)
Sets this check box's group to the specified check box group.
15 void setLabel(String label)
Sets this check box's label to be the string argument.
16 void setState(boolean state)
Sets the state of this check box to the specified state.

AWT TextField Class


Introduction

18
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

The textField component allows the user to edit single line of text.When the user types a key in
the text field the event is sent to the TextField. The key event may be key pressed, Key released
or key typed. The key event is passed to the registered KeyListener. It is also possible to for an
ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by
pressing the return key.
Class declaration
Following is the declaration for java.awt.TextField class:
public class TextField
extends TextComponent
Class constructors
S.N. Constructor & Description

1 TextField()
Constructs a new text field.
2 TextField(int columns)
Constructs a new empty text field with the specified number of columns.
3 TextField(String text)
Constructs a new text field initialized with the specified text.
4 TextField(String text, int columns)
Constructs a new text field initialized with the specified text to be displayed, and wide
enough to hold the specified number of columns.

Class methods
S.N. Method & Description

• void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this text field.

void addNotify()
Creates the TextField's peer.
• AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this TextField.
• ActionListener[] getActionListeners()

19
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Returns an array of all the action listeners registered on this textfield.


• int getColumns()
Gets the number of columns in this text field.
• Dimension getMinimumSize()
Gets the minumum dimensions for this text field.
• Dimension getPreferredSize()
Gets the preferred size of this text field.
• Dimension getPreferredSize(int columns)
Gets the preferred size of this text field with the specified number of columns.
• protected String paramString()
Returns a string representing the state of this TextField.
• void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from
this text field.
• void setColumns(int columns)
Sets the number of columns in this text field.
• void setText(String t)
Sets the text that is presented by this text component to be the specified text.

AWT List Class


Introduction
The List represents a list of text items. The list can be configured that user can choose either one
item or multiple items.
Class declaration
Following is the declaration for java.awt.List class:
public class List
extends Component
implements ItemSelectable, Accessible
Class constructors

20
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

S.N. Constructor & Description

1 List()
Creates a new scrolling list.
2 List(int rows)
Creates a new scrolling list initialized with the specified number of visible lines.
3 List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified number of rows.

Class methods
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this List.
S.N. Method & Description

void add(String item)


Adds the specified item to the end of scrolling list.

void add(String item, int index)


Adds the specified item to the the scrolling list at the position indicated by the
index.

void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this list.

void addItem(String item)


Deprecated. replaced by add(String).

void addItem(String item, int index)


Deprecated. replaced by add(String, int).

void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this list.

void addNotify()
Creates the peer for the list.

21
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

void delItems(int start, int end)


Deprecated. As of JDK version 1.1, Not for public use in the future. This method
is expected to be retained only as a package private method.

void deselect(int index)


Deselects the item at the specified index.

String getItem(int index)


Gets the item associated with the specified index.

int getItemCount()
Gets the number of items in the list.

ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this list.

String[] getItems()
Gets the items in the list.

Dimension getMinimumSize()
Determines the minimum size of this scrolling list.

Dimension getMinimumSize(int rows)


Gets the minumum dimensions for a list with the specified number of rows.

Dimension getPreferredSize()
Gets the preferred size of this scrolling list.

Dimension getPreferredSize(int rows)


Gets the preferred dimensions for a list with the specified number of rows.

int getRows()
Gets the number of visible lines in this list.

int getSelectedIndex()
Gets the index of the selected item on the list,

int[] getSelectedIndexes()

22
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Gets the selected indexes on the list.

String getSelectedItem()
Gets the selected item on this scrolling list.

String[] getSelectedItems()
Gets the selected items on this scrolling list.

boolean isMultipleMode()
Determines whether this list allows multiple selections.

void makeVisible(int index)


Makes the item at the specified index visible.

void remove(int position)


Removes the item at the specified position from this scrolling list.

void remove(String item)


Removes the first occurrence of an item from the list.

void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events
from this list.

void removeAll()
Removes all items from this list.

void removeItemListener(ItemListener l)
Removes the specified item listener so that it no longer receives item events from
this list.

void removeNotify()
Removes the peer for this list.

void replaceItem(String newValue, int index)


Replaces the item at the specified index in the scrolling list with the new string.

void select(int index)

23
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Selects the item at the specified index in the scrolling list.

void setMultipleMode(boolean b)
Sets the flag that determines whether this list allows multiple selections.

AWT Choice Class


Introduction
Choice control is used to show pop up menu of choices. Selected choice is shown on the top of
the menu.
Class declaration
Following is the declaration for java.awt.Choice class:
public class Choice
extends Component
implements ItemSelectable, Accessible
Class constructors
S.N. Constructor & Description

1 Choice() ()
Creates a new choice menu.

Class methods
S.N. Method & Description

1 void add(String item)


Adds an item to this Choice menu.
2 void addItem(String item)
Obsolete as of Java 2 platform v1.1.
3 void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this Choice menu.
4 void addNotify()
Creates the Choice's peer.
5 int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().

24
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

6 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Choice.
7 String getItem(int index)
Gets the string at the specified index in this Choice menu.
8 int getItemCount()
Returns the number of items in this Choice menu.
9 ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this choice.
10 <T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Choice.
11 int getSelectedIndex()
Returns the index of the currently selected item.
12 String getSelectedItem()
Gets a representation of the current choice as a string.
13 Object[] getSelectedObjects()
Returns an array (length 1) containing the currently selected item.
14 void insert(String item, int index)
Inserts the item into this choice at the specified position.
15 protected String paramString()
Returns a string representing the state of this Choice menu.
16 protected void processEvent(AWTEvent e)
Processes events on this choice.
17 protected void processItemEvent(ItemEvent e)
Processes item events occurring on this Choice menu by dispatching them to any
registered ItemListener objects.
18 void remove(int position)

25
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Removes an item from the choice menu at the specified position.


19 void remove(String item)
Removes the first occurrence of item from the Choice menu.
20 void removeAll()
Removes all items from the choice menu.
21 void removeItemListener(ItemListener l)
Removes the specified item listener so that it no longer receives item events from this
Choice menu.
22 void select(int pos)
Sets the selected item in this Choice menu to be the item at the specified position.
23 void select(String str)
Sets the selected item in this Choice menu to be the item whose name is equal to the
specified string.
Example:

import java.lang.*;

import java.awt.*;

class Awtclassex extends Frame

Awtclassex()

Button b = new Button("Ok");

b.setBounds(350,350,50,50); add(b);

Label lb;

lb=new Label("Welcome to BCA III"); lb.setBounds(50,50,200,30); add(lb);

26
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

TextField text;

text=new TextField("We are studing Advance Java");

text.setBounds(70,100, 230,40); add(text);

Choice ch=new Choice(); ch.setBounds(100,150, 100,100);

ch.add("Chap1"); ch.add("Chap2"); ch.add("Chap3"); add(ch);

List li= new List(3);

li.setBounds(100,250, 100,100); li.add("Chap1"); li.add("Chap2");

li.add("Chap3"); add(li);

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

public static void main(String args[])

Awtclassex ex1 = new Awtclassex();

The Delegation Event Model


The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events. Its concept is quite simple: a
source generates an event and sends it to one or more listeners. In this scheme, the listener
simply waits until it receives an event. Once an event is received, the listener processes the event
and then returns. The advantage of this design is that the application logic that processes events
is cleanly separated from the user interface logic that generates those events. A user interface
element is able to “delegate” the processing of an event to a separate piece of code.
27
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want
to receive them. This is a more efficient way to handle events than the design used by the old
Java 1.0 approach. Previously, an event was propagated up the containment hierarchy until it was
handled by a component. This required components to receive events that they did not process,
and it wasted valuable time. The delegation event model eliminates this overhead.
Events

In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are pressing a button, entering
a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user
operations could also be cited as examples.

Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software
or hardware failure occurs, or an operation is completed. You are free to define events that are
appropriate for your application.

Event Sources

A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. A source must register
listeners in order for the listeners to receive notifications about a specific type of event. Each
type of event has its own registration method. Here is the

general form:

public void addTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example, the
method that registers a keyboard event listener is called addKeyListener( ). The method that
registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs,
all registered listeners are notified and receive a copy of the event object. This is known as
multicasting the event. In all cases, notifications are sent only to listeners that register to receive
them.

Some sources may allow only one listener to register. The general form of such a method is this:

public void addTypeListener(TypeListener el)

throws java.util.TooManyListenersException

28
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Here, Type is the name of the event, and el is a reference to the event listener. When such an
event occurs, the registered listener is notified. This is known as unicasting the event.

A source must also provide a method that allows a listener to unregister an interest in a specific
type of event. The general form of such a method is this:

public void removeTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example, to
remove a keyboard listener, you would call removeKeyListener( ).

The methods that add or remove listeners are provided by the source that generates events. For
example, the Component class provides methods to add and remove keyboard and mouse event
listeners.

Event Listeners

A listener is an object that is notified when an event occurs. It has two major requirements.

First, it must have been registered with one or more sources to receive notifications about
specific types of events. Second, it must implement methods to receive and process these
notifications.

The methods that receive and process events are defined in a set of interfaces found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved. Any object may receive and process one or
both of these events if it provides an implementation of this interface. Many other listener
interfaces are discussed later in this and other chapters.

Event Classes

The classes that represent events are at the core of Java’s event handling mechanism. At the root
of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all
events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event.

EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method

returns the source of the event. Its general form is shown here:

Object getSource( )

As expected, toString( ) returns the string equivalent of the event.


29
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

The class AWTEvent, defined within the java.awt package, is a subclass of EventObject.

It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation
event model. Its getID( ) method can be used to determine the type of the event. The signature of
this method is shown here:

int getID( )

• EventObject is a superclass of all events.

• AWTEvent is a superclass of all AWT events that are handled by the delegation event model

30
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

Sources of Events:

Event Listener Interfaces:

31
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

The ActionEvent Class


An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected. The ActionEvent class defines four integer constants that can be used to identify
any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK,
and SHIFT_MASK. In addition, there is an integer constant, ACTION_ PERFORMED, which
can be used to identify action events.

ActionEvent has these three constructors:

ActionEvent(Object src, int type, String cmd)

ActionEvent(Object src, int type, String cmd, int modifiers)

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

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

You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:

String getActionCommand( )

For example, when a button is pressed, an action event is generated that has a command name
equal to the label on that button.

The getModifiers( ) method returns a value that indicates which modifier keys (ALT, CTRL,
META, and/or SHIFT) were pressed when the event was generated. Its form is shown here:

int getModifiers( )

The method getWhen( ) returns the time at which the event took place. This is called the event’s
timestamp. The getWhen( ) method is shown here:

long getWhen( )

32
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

The KeyEvent Class

A KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and
KEY_TYPED. The first two events are generated when any key is pressed or released. The last
event occurs only when a character is generated.

Remember, not all keypresses result in characters. For example, pressing SHIFT does not
generate a character. There are many other integer constants that are defined by KeyEvent. For
example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and letters. Here are some others:

The VK constants specify virtual key codes and are independent of any modifiers, such as

control, shift, or alt.

KeyEvent is a subclass of InputEvent. Here is one of its constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of the event is
specified by type

The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar(
), which returns the character that was entered, and getKeyCode( ), which returns the key code.
Their general forms are shown here:

char getKeyChar( )

int getKeyCode( )

If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

33
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

<applet code="SimpleKey" width=300 height=100>

</applet>

*/

public class SimpleKey extends Applet

implements KeyListener {

String msg = "";

int X = 10, Y = 20; // output coordinates

public void init() {

addKeyListener(this);

public void keyPressed(KeyEvent ke) {

showStatus("Key Down");

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

public void keyTyped(KeyEvent ke) {

msg += ke.getKeyChar();

repaint();

// Display keystrokes.

public void paint(Graphics g) {

g.drawString(msg, X, Y);

}}

34
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the following integer

constants that can be used to identify them:

MouseEvent is a subclass of InputEvent. Here is one of its constructors:

MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks,
boolean triggersPopup)

Here, src is a reference to the component that generated the event. The type of the event is
specified by type. The system time at which the mouse event occurred is passed in when. The
modifiers argument indicates which modifiers were pressed when a mouse event occurred.

The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.

Two commonly used methods in this class are getX( ) and getY( ). These return the X and Y
coordinates of the mouse within the component when the event occurred. Their forms are shown
here:

int getX( )

int getY( )

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MouseEvents" width=300 height=100>

</applet>

35
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

*/

public class MouseEvents extends Applet

implements MouseListener, MouseMotionListener {

String msg = "";

int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {

addMouseListener(this);

addMouseMotionListener(this);

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse clicked.";

repaint();

// Handle mouse entered.

public void mouseEntered(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse entered.";

repaint();

}
36
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse exited.";

repaint();

// Handle button pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

The WindowEvent Class


37
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

There are ten types of window events. The WindowEvent class defines integer constants that can
be used to identify them. The constants and their meanings are shown here:

WindowEvent is a subclass of ComponentEvent. It defines several constructors. The first is

WindowEvent(Window src, int type)

Here, src is a reference to the object that generated this event. The type of the event is type.

The next three constructors offer more detailed control:

WindowEvent(Window src, int type, Window other)

WindowEvent(Window src, int type, int fromState, int toState)

WindowEvent(Window src, int type, Window other, int fromState, int toState)

Here, other specifies the opposite window when a focus or activation event occurs. The
fromState specifies the prior state of the window, and toState specifies the new state that the
window will have when a window state change occurs.

A commonly used method in this class is getWindow( ). It returns the Window object that
generated the event. Its general form is shown here:

Window getWindow( )

WindowEvent also defines methods that return the opposite window (when a focus or activation
event has occurred), the previous window state, and the current window state.

These methods are shown here:

Window getOppositeWindow( )

38
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

int getOldState( )

int getNewState( )

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="AppletFrame" width=300 height=50>

</applet>

*/

// Create a subclass of Frame.

class SampleFrame extends Frame {

SampleFrame(String title) {

super(title);

// create an object to handle window events

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

public void paint(Graphics g) {

g.drawString("This is in frame window", 10, 40);

class MyWindowAdapter extends WindowAdapter {

SampleFrame sampleFrame;

public MyWindowAdapter(SampleFrame sampleFrame) {


39
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events

this.sampleFrame = sampleFrame;

public void windowClosing(WindowEvent we) {

sampleFrame.setVisible(false);

}}

// Create frame window.

public class AppletFrame extends Applet {

Frame f;

public void init() {

f = new SampleFrame("A Frame Window");

f.setSize(250, 250);

f.setVisible(true);

public void start() {

f.setVisible(true);

public void stop() {

f.setVisible(false);

public void paint(Graphics g) {

g.drawString("This is in applet window", 10, 20);

}}

40

You might also like