You are on page 1of 60

Unit 8 - AWT and Event handling

in Java
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Contents
1. List and discuss AWT classes

2. Discuss about Window fundamentals - Container, Panel, Window, Frame, Canvas

3. Discuss working with frame windows

4. Distinguish different Graphics controls.

5. Discuss working with color

6. Discuss Working with Fonts

7. Explain AWT controls and handlings – labels, buttons, checkboxes, lists, scrollbars, Text fields, text area, menus, dialog
boxes.

8. Explain the Two event handling mechanisms.

9. Discuss about The Delegation event model – events, event sources and event Listeners

10. List and explain event Classes

11. Explain various sources of events.

12. Describe event listener interfaces.

13. Explain mouse and keyboard events.

14. Differentiate between Adapter classes, Inner classes.


Abstract Window Toolkit
• AWT stands for Abstract Window Toolkit. It
is a Java package that can be imported
as java.awt.* and that consists of platform-
independent windowing, graphics, and user
interface tools for programmers to use when
building up applets and/or stand-alone Java
applications.

• AWT contains large number of classes and


methods that allows you to create and manage
windows GUI application.

• AWT is the foundation upon which Swing is


made and Swing has rich implementation of
GUI controls and light-weighted nature.

• AWT API was introduced in JDK 1.0. Most of


the AWT components have become obsolete
and should be replaced by newer Swing
components.
List of AWT classes
• Components • java.awt.event • java.awt.im
Hierarchy ▫ Listener • java.awt.image
1. Component
▫ Events ▫ Image
2. Container
3. UIComponents ▫ Support ▫ Consumer
4. Menu • java.awt.font ▫ ColorModel
• LayoutManager ▫ Font ▫ DataBuffer
• Focus ▫ TextLayout ▫ ImageOp
• Graphics ▫ Attribute ▫ Raster
• Paint ▫ Glyph ▫ SampleModel
• Toolkit
• java.awt.geom ▫ Misc
• Exceptions
▫ Shapes ▫ java.awt.image.renderable
• java.awt.color
• java.awt.datatransfer ▫ Lines • java.awt.print
• java.awt.dnd ▫ Rects
▫ DragGesture ▫ Asym
▫ DragSource ▫ Point
▫ DropTarget ▫ Misc
Java Package - java.awt.*
• AWT provides a platform-independent and device-independent interface to
develop graphic programs that runs on all platforms, such as Windows, Mac, and
Linux.

• AWT is huge! It consists of 12 packages (Swing is even bigger, with 18 packages


as of JDK 1.8).

• Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used.

1. The java.awt package contains the core AWT graphics classes:


▫ GUI Component classes (such as Button, TextField, and Label),
▫ GUI Container classes (such as Frame, Panel, Dialog and ScrollPane),
▫ Layout managers (such as FlowLayout, BorderLayout and GridLayout),
▫ Custom graphics classes (such as Graphics, Color and Font).

2. The java.awt.event package supports event handling:


▫ Event classes (such as ActionEvent, MouseEvent, KeyEvent and WindowEvent),
▫ Event Listener Interfaces (such as ActionListener, MouseListener, KeyListener and
WindowListener),
▫ Event Listener Adapter classes (such as MouseAdapter, KeyAdapter, and
WindowAdapter).
Containers and Components

• There are two types of GUI elements:


1. Component:
 Components are elementary GUI entities (such as Button, Label, and TextField.)
and are also called controls which allow users to interact with (or control) the
application through these components (such as button-click and text-entry).
2. Container:
 Containers (such as Frame and Panel) are used to hold components in a specific
layout (such as flow or grid). A container can also hold sub-containers.
 A Frame has a title bar (containing an icon, a title, and the minimize/maximize/close
buttons), an optional menu bar and the content display area.
 A Panel is a rectangular area used to group related GUI components in a certain layout. 
• In a GUI program, a component must be kept in a container.
Hierarchy of the
AWT Container Classes
• A Frame provides the "main window" for the
GUI .

• An AWT Dialog is a "pop-up window" used


for interacting with the users.
▫ A Dialog has a title-bar (containing an icon, a
title and a close button) and a content display
area.

• An AWT Applet (in package java.applet) is
the top-level container for an applet, which is
a Java program running inside a browser. 

• Panel: a rectangular box under a higher-


level container, used to layout a set of related
GUI components in pattern such as grid or
flow.

• ScrollPane: provides automatic horizontal


and/or vertical scrolling for a single child
component.
AWT Component Classes

• AWT provides many ready-made and reusable GUI components.


• The frequently-used are:
1. Button,
2. TextField,
3. Label,
4. Checkbox,
5. CheckboxGroup 
6. Radio buttons,
7. List, and 
8. Choice.
AWT Component Classes cont…
AWT Component Classes cont…
AWT Component Classes cont…
AWT Component Classes cont…
AWT Component Classes cont…
AWT Container – Frame & its Methods
Steps for Constructing a Component and Adding the Component into
Container
• Three steps are necessary to create and place a GUI component:
1. Declare the component with an identifier (name);
2. Construct the component by invoking an appropriate constructor via the new operator;
3. Identify the container (such as Frame or Panel) designed to hold this component. The container
can then add this component onto itself via aContainer1.add(aComponent1) method.
Every container has a add(Component) method. Take note that it is the container that
actively and explicitly adds a component onto itself, instead of the other way.

• An Anonymous Instance
▫ You can create a Label without specifying an identifier, called anonymous instance.
▫ In the case, the Java compiler will assign an anonymous identifier for the allocated object.
▫ You will not be able to reference an anonymous instance in your program after it is created. 
Example – Frame Creation
import java.awt.*;

class FrameDemo {
public static void main(String[] args)

{
Frame f=new Frame();
f.setTitle("myframe");
f.setBackground(Color.cyan);
f.setForeground(Color.red);
f.setLayout(new FlowLayout());

Button b1=new Button("Submit");


Button b2=new Button("Cancel");
f.add(b1);
f.add(b2);
f.setSize(500,300);
f.setVisible(true);
}
}
Example - Creating an AWT frame
import java.awt.*;
class AWTFrame extends Frame
{
    public AWTFrame()
    {
    setTitle("AWT Frame"); // Set the title
    setSize(400,400); // Set size to the frame
    setVisible(true); // Make the frame visible
    setBackground(Color.red); // Set the background
    setExtendedState(MAXIMIZED_BOTH); // Make the frame maximized
    setCursor(Cursor.HAND_CURSOR); // Deprecated
    }
    
    public static void main(String args[])
    {
    new AWTFrame();
System.out.println(“Return to DOS prompt and press ctrl+C to quit”);
    }
}
Example – Employee Form
import java.awt.*;
class AddEmployee extends Frame {
Label user_id, fn, ln, ftn, DOB, gender, country, mobile, address;
TextField ID, f_name, l_name, Father1, dob, add1, mobile_no;
Choice c;
Button b1, b2, b3, b4;
CheckboxGroup cg1;
Checkbox male, female;

public AddEmployee() {
setTitle("Employee Detail");
setBackground(Color.cyan);
setLayout(null);

fn=new Label("Emp Name");


ftn=new Label("Father Name:");
DOB=new Label("Date of birth:");
gender=new Label(“Gender:");
address=new Label("Address:");
country=new Label("Country:");
mobile=new Label("Mobile no:");

Font f=new Font("Arial", Font.BOLD, 15);


fn.setFont(f); ftn.setFont(f);
DOB.setFont(f); gender.setFont(f);
address.setFont(f);
country.setFont(f); mobile.setFont(f);
fn.setBounds(20,50,100,40);
ftn.setBounds(20,100,100,40);
DOB.setBounds(20,150,100,40);
gender.setBounds(20,200,100,40);
address.setBounds(20,250,100,50);
country.setBounds(20,300,100,50);
mobile.setBounds(20,350,100,40);

add(fn);
add(ftn);
add(DOB);
add(gender);
add(address);
add(country);
add(mobile);

f_name=new TextField("",20);
Father1=new TextField("",20);
dob=new TextField("Day/Month/Year",20);
add1=new TextField("",40);
mobile_no=new TextField("",20);

f_name.setBounds(200,60,200,20);
Father1.setBounds(200,110,200,20);
dob.setBounds(200,160,140,20);
add1.setBounds(200,260,200,20);
mobile_no.setBounds(200,360,130,20);
add(f_name);
add(Father1);
add(dob);

cg1=new CheckboxGroup();
male=new Checkbox("Male", cg1, true);
female=new Checkbox("Female", cg1, false);
add(male); add(female);

male.setBounds(200,200,50,50);
female.setBounds(300,200,60,50);

add(add1);

c=new Choice();
c.addItem("City");
c.addItem("New Delhi");
c.addItem("Raipur");
c.addItem("Chandigarh");
c.addItem("Dehradun");
c.addItem("Patna");
c.addItem("Dispur");
c.addItem("Other");
c.setBounds(200,310,130,20);

add(c); add(c); add(c); add(c); add(c); add(c); add(c); add(c); add(c); add(c); add(c); add(c);
add(c); add(mobile_no);
Font fa=new Font("Arial", Font.BOLD, 15);

b1=new Button("Submit");
b2=new Button("Exit");
b3=new Button("AddNew");

b1.setBounds(170,430,80,30);
b2.setBounds(270,430,80,30);
b3.setBounds(370,430,80,30);
b1.setBackground(Color.pink);
b2.setBackground(Color.pink);
b3.setBackground(Color.pink);

add(b1); add(b2); add(b3);

b1.setFont(fa);
b2.setFont(fa);
b3.setFont(fa);

setSize(600,500);
setVisible(true);
} //cons
} // class

class Employee {
public static void main(String s[]) {
AddEmployee obj=new AddEmployee(); } }
Java adopts the so-called "Event-Driven" (or "Event-Delegation") programming
model for event-handling, similar to most of the visual programming languages
(such as Visual Basic and Delphi).

In event-driven programming, a piece of event-handling codes is executed (or called


back by the graphics subsystem) when an event has been fired in response to an
user input (such as clicking a mouse button or hitting the ENTER key).
Event Handling
• In general you can not perform any operation on dummy GUI
screen even any button click or select any item.

• To perform some operation on these dummy GUI screen you need


some predefined classes and interfaces. All these type of classes
and interfaces are available in java.awt.event package.

• Changing the state of an object is known as an event.

• The process of handling the request in GUI screen is known


as event handling (event represent an action).

Note: In event handling mechanism event represent an action class


and Listener represent an interface. Listener interface always
contains abstract methods so here you need to write your own logic
Java Event Handling
• The AWT's event-handling classes are kept in
package java.awt.event

• Three objects are involved in the event-handling:


1. a source, 
2. listener(s) and
3. an event object.

• The source object (such as Button and Textfield)


interacts with the user. Upon triggered, it creates
an event object. This event object will be
messaged to all the registered listener object(s),
and an appropriate event-handler method of the
listener(s) is called-back to provide the response.

• In other words, triggering a source fires an event


to all its listener(s), and invoke an appropriate
handler of the listener(s).
/* Program to
Demonstrate
Button Event
handling */
/* Program to
Demonstrate
Button Event
handling */
/* Program to Demonstrate Checkbox Event handling */

• For handling event for RadioButton,


List, Choice, checkbox you need to
use ItemEvent class and
ItemListener interface.

• ItemEvent class and ItemListener


interface are associated with radio
button, checkbox list, choice. This
logic can be written in
itemStateChanged() whenever we
want to perform operation while
changed the option in those
component.

GUI Component Event Listener Method (abstract method)


class Interface
RadioButton, Checkbox, ItemEvent ItemListener public void
List, Choice itemStateChanged(ItemEvent e)
/* Program to
Demonstrate
Checkbox
Event
handling */
/* Program to
Demonstrate
Checkbox
Event
handling */
AWT Layout Management
• Layout is a logical container used to arrange the GUI
component in proper order within the frame, in java.awt
package some of the layout is existing an predefined
classes as shown below;
1.FlowLayout
2.BoarderLayout
3.GridLayout
4.GridbagLayout
5.CardLayout
Basic Layout Managers
Default for java.applet.Applet, java.awt.Panel and java.swing.Jpanel. Places components
sequentially (left to right) in the order they were added. You can specify the order.
Flow
This is the most basic layout manager, components are placed from left to right as they were added,
Layout
when the edge is reached the components are put on the next line. You can align the components left,
right or center (default).

Default for the content panes of JFrame and JApplets. Arranges the components into five
Border areas: North, South, East, West, and Center
Layout Components are positioned in a five different areas: North, South, East, West or Center. If you do not
specify a particular area the other areas will use this space by expanding.

Arranges the components into rows and columns


Grid This layout manager divides the container into a grid so that components can be placed in rows and
Layout columns. Every component will have the same width and height, the components are added to the grid
starting at the top left cell and proceeding left-to-right until the row is full, then go onto the next row.

Advanced Layout Managers

Box Allows components to be arranged left-to-right or top-to-bottom in a container


Layout Arranges GUI components horizontally along the x-axis or vertically along the y-axis of a container.

Stacks components like a deck of cards


Card
arranges GUI components into a "deck" of cards where only the top card is visable, any card in the deck
Layout
can be placed at the top (thus visable). Each card is normally a Panel which can use any layout manager.

similar to GridLayout. unlike GridLayout each component size can vary and components can


GridBag be added in any order.
Layout This is the most complex of the layout managers, it is the same as GridLayout but more flexible as the
components can be different sizes
File Based – Event Handling
Application Form with ‘Save to’ Option
Check Notes section for complete Program
Example - Simple Notepad
Example – Sudoku Game Check Notes Section
Example - Layout
Example – Rounded Rectangle
Complete Notepad in Java Check Notes Section
Drawing Different Shapes using Swings Check Notes Section

You might also like