Chapter 2: Working With Frames AWT Controls and Events
Chapter 2: Working With Frames AWT Controls and Events
Chapter 2: Working With Frames AWT Controls and Events
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
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)
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
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
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)
{
// Main Method
public static void main(String[] args)
{
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:
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
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.
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
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.
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
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
20
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
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 addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this list.
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
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 getPreferredSize()
Gets the preferred size of this scrolling list.
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
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 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.
23
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
void setMultipleMode(boolean b)
Sets the flag that determines whether this list allows multiple selections.
1 Choice() ()
Creates a new choice menu.
Class methods
S.N. Method & Description
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
import java.lang.*;
import java.awt.*;
Awtclassex()
b.setBounds(350,350,50,50); add(b);
Label lb;
26
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
TextField text;
li.add("Chap3"); add(li);
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:
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:
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:
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)
EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method
returns the source of the event. Its general form is shown here:
Object getSource( )
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( )
• 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:
31
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
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
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
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( )
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>
*/
implements KeyListener {
addKeyListener(this);
showStatus("Key Down");
showStatus("Key Up");
msg += ke.getKeyChar();
repaint();
// Display keystrokes.
g.drawString(msg, X, Y);
}}
34
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
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>
35
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
*/
addMouseListener(this);
addMouseMotionListener(this);
// save coordinates
mouseX = 0;
mouseY = 10;
repaint();
// save coordinates
mouseX = 0;
mouseY = 10;
repaint();
}
36
BCA III Yr. V SEM Advance JAVA
Chapter 2: Working with Frames AWT controls and Events
// save coordinates
mouseX = 0;
mouseY = 10;
repaint();
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
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:
Here, src is a reference to the object that generated this event. The type of the event is type.
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.
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>
*/
SampleFrame(String title) {
super(title);
addWindowListener(adapter);
SampleFrame sampleFrame;
this.sampleFrame = sampleFrame;
sampleFrame.setVisible(false);
}}
Frame f;
f.setSize(250, 250);
f.setVisible(true);
f.setVisible(true);
f.setVisible(false);
}}
40