0% found this document useful (0 votes)
4 views41 pages

Java Unit-5-Awt

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, featuring platform-dependent components and a hierarchy of classes like Frame and Panel. It contrasts with Java Swing, which is built on AWT, providing lightweight and platform-independent components. The document also includes examples of creating AWT and Swing applications, highlighting key classes and methods used in both frameworks.

Uploaded by

kaluvalatharun47
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views41 pages

Java Unit-5-Awt

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, featuring platform-dependent components and a hierarchy of classes like Frame and Panel. It contrasts with Java Swing, which is built on AWT, providing lightweight and platform-independent components. The document also includes examples of creating AWT and Swing applications, highlighting key classes and methods used in both frameworks.

Uploaded by

kaluvalatharun47
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 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 [Link] package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.

Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.

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

The hierarchy of Java AWT classes are given below.

1
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.

It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.

Note: A container itself is a component (see the above diagram), therefore we can add a container
inside container.

Types of containers: There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. 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.

Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by default false.

2
Java AWT Example: To create simple AWT example, you need a frame. There are two ways to create
a GUI using Frame in AWT.

 By extending Frame class (inheritance)


 By creating the object of Frame class (association)

AWT Example by Inheritance: [Link]

import [Link].*;

public class AWTExample1 extends Frame {

AWTExample1() {

Button b = new Button("Click Me!!");

[Link](30,100,80,30);

add(b);

setSize(300,300);

setTitle("This is our basic AWT example");

setLayout(null);

setVisible(true);

public static void main(String args[]) {

AWTExample1 f = new AWTExample1();

} }

The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that
sets the position of the awt button.

Output:

3
AWT Example by Association: [Link]

import [Link].*;

class AWTExample2 {

AWTExample2() {

Frame f = new Frame();

Label l = new Label("Employee id:");

Button b = new Button("Submit");

TextField t = new TextField();

[Link](20, 80, 80, 30);

[Link](20, 100, 80, 30);

[Link](100, 100, 80, 30);

[Link](b);

[Link](l);

[Link](t);

[Link](400,300);

[Link]("Employee info");

[Link](null);

[Link](true);

} public static void main(String args[]) {

AWTExample2 awt_obj = new AWTExample2();

} }

Output:

4
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.

5) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and
controller acts as an interface between model and view.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of
desktop applications.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

5
Commonly used Methods of Component class:

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

6
Java Swing Examples: There are two ways to create a frame:

By creating the object of Frame class (association)

By extending Frame class (inheritance)

Simple Java Swing Example: File: [Link]

import [Link].*;

public class FirstSwingExample {

public static void main(String[] args) {

JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton

[Link](130,100,100, 40);//x axis, y axis, width, height

[Link](b);//adding button in JFrame

[Link](400,500);//400 width and 500 height

[Link](null);//using no layout managers

[Link](true);//making the frame visible

7
JContainer components

Java JFrame: The [Link] class is a type of container which inherits the [Link]
class. JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI. Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.

Nested Class

Modifier and Class Description


Type

protected class [Link] This class implements accessibility support for the JFrame
class.

Fields

Modifier and Type Field Description

protected accessibleContext The accessible context property.


AccessibleContext

static int EXIT_ON_CLOSE The exit application default window close operation.

protected JRootPane rootPane The JRootPane instance that manages the


contentPane and optional menuBar for this frame, as
well as the glassPane.

protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be
forwarded to the contentPane.

Constructors

Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration gc) It creates a Frame in the specified GraphicsConfiguration of a

8
screen device and a blank title.

JFrame(String title) It creates a new, initially invisible Frame with the specified title.

JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen device.

Useful Methods

Modifier and Method Description


Type

protected void addImpl(Component comp, Object Adds the specified child Component.
constraints, int index)

protected createRootPane() Called by the constructor methods to


JRootPane create the default rootPane.

protected void frameInit() Called by the constructors to init the


JFrame properly.

void setContentPane(Containe contentPane) It sets the contentPane property

void setIconImage(Image image) It sets the image to be displayed as the


icon for this window.

void setJMenuBar(JMenuBar menubar) It sets the menubar for this frame.

void setLayeredPane(JLayeredPane layeredPane) It sets the layeredPane property.

JFrame Example

import [Link];

import [Link];

import [Link];

import [Link];

9
import [Link];

public class JFrameExample {

public static void main(String s[]) {

JFrame frame = new JFrame("JFrame Example");

JPanel panel = new JPanel();

[Link](new FlowLayout());

JLabel label = new JLabel("JFrame By Example");

JButton button = new JButton();

[Link]("Button");

[Link](label);

[Link](button);

[Link](panel);

[Link](200, 300);

[Link](null);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

} }

Output

JApplet class in Applet

As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet class
extends the Applet class.

10
Example of EventHandling in JApplet:

import [Link].*;

import [Link].*;

import [Link].*;

public class EventJApplet extends JApplet implements ActionListener{

JButton b;

JTextField tf;

public void init(){

tf=new JTextField();

[Link](30,40,150,20);

b=new JButton("Click");

[Link](80,150,70,40);

add(b);add(tf);

[Link](this);

setLayout(null);

public void actionPerformed(ActionEvent e){

[Link]("Welcome");

} }

In the above example, we have created all the controls in init() method because it is invoked only once.

[Link]

<html>

<body>

<applet code="[Link]" width="300" height="300">

</applet>

</body>

</html>

11
Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.

It doesn't have title bar.

JPanel class declaration

public class JPanel extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.

JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.

Java JPanel Example

import [Link].*;

import [Link].*;

public class PanelExample {

PanelExample()

JFrame f= new JFrame("Panel Example");

JPanel panel=new JPanel();

[Link](40,80,200,200);

[Link]([Link]);

JButton b1=new JButton("Button 1");

[Link](50,100,80,30);

12
[Link]([Link]);

JButton b2=new JButton("Button 2");

[Link](100,100,80,30);

[Link]([Link]);

[Link](b1); [Link](b2);

[Link](panel);

[Link](400,400);

[Link](null);

[Link](true);

} public static void main(String args[])

{ new PanelExample();

Output:

JSwing components

Java JButton: The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

13
JButton class declaration

public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example

import [Link].*;

public class ButtonExample {

14
public static void main(String[] args) {

JFrame f=new JFrame("Button Example");

JButton b=new JButton("Click Here");

[Link](50,100,95,30);

[Link](b);

[Link](400,400);

[Link](null);

[Link](true);

Output:

Java JLabel: The object of JLabel 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 an application but a user cannot
edit it directly. It inherits JComponent class.

JLabel class declaration

public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string
for the title.

15
JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will display.

void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.

Java JLabel Example

import [Link].*;

class LabelExample

{ public static void main(String args[])

JFrame f= new JFrame("Label Example");

JLabel l1,l2;

l1=new JLabel("First Label.");

[Link](50,50, 100,30);

l2=new JLabel("Second Label.");

16
[Link](50,100, 100,30);

[Link](l1); [Link](l2);

[Link](300,300);

[Link](null);

[Link](true);

Output:

Java JTextField: The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.

JTextField class declaration

public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.

17
JTextField(int columns) Creates a new empty TextField with the specified number of columns.

Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent source, or
null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it no


removeActionListener(ActionListener l) longer receives action events from this textfield.

Java JTextField Example

import [Link].*;

class TextFieldExample

public static void main(String args[])

{ JFrame f= new JFrame("TextField Example");

JTextField t1,t2;

t1=new JTextField("Welcome to Javatpoint.");

[Link](50,100, 200,30);

t2=new JTextField("AWT Tutorial");

[Link](50,150, 200,30);

[Link](t1); [Link](t2);

[Link](400,400);

[Link](null);

18
[Link](true);

Output:

Java JTextArea: The object of a JTextArea class is a multi line region that displays text. It allows
the editing of multiple line text. It inherits JTextComponent class

JTextArea class declaration

public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text


initially.

JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.

JTextArea(String s, int Creates a text area with the specified number of


row, int column) rows and columns that displays specified text.

Commonly used Methods:

19
Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int It is used to insert the specified text on the


position) specified position.

void append(String s) It is used to append the given text to the end of


the document.

Java JTextArea Example

import [Link].*;

public class TextAreaExample

{ TextAreaExample(){

JFrame f= new JFrame();

JTextArea area=new JTextArea("Welcome to javatpoint");

[Link](10,30, 200,200);

[Link](area);

[Link](300,300);

[Link](null);

[Link](true);

public static void main(String args[])

{ new TextAreaExample();

}}

20
Java LayoutManagers

 The LayoutManagers are used to arrange components in a particular manner.


 The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms.
 LayoutManager is an interface that is implemented by all the classes of layout managers.

There are the following classes that represent the layout managers:

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] etc.

Java 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 a 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

Constructors of BorderLayout class:

BorderLayout(): creates a border layout but with no gaps between the components.

BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.

Example : FileName: [Link]

import [Link].*;

import [Link].*;

public class Border

{ JFrame f;

Border()

21
{ f = new JFrame();

JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH

JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH

JButton b3 = new JButton("EAST");; // the button will be labeled as EAST

JButton b4 = new JButton("WEST");; // the button will be labeled as WEST

JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

[Link](b1, [Link]); // b1 will be placed in the North Direction

[Link](b2, [Link]); // b2 will be placed in the South Direction

[Link](b3, [Link]); // b2 will be placed in the East Direction

[Link](b4, [Link]); // b2 will be placed in the West Direction

[Link](b5, [Link]); // b2 will be placed in the Center

[Link](300, 300);

[Link](true);

public static void main(String[] args) {

new Border();

} }

Output:

22
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.

Constructors of GridLayout class

GridLayout(): creates a grid layout with one column per component in a row.

GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.

GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns along with given horizontal and vertical gaps.

Example : FileName: [Link]

import [Link].*;

import [Link].*;

public class GridLayoutExample

JFrame frameObj;

GridLayoutExample()

{ frameObj = new JFrame();

JButton btn1 = new JButton("1");

JButton btn2 = new JButton("2");

JButton btn3 = new JButton("3");

JButton btn4 = new JButton("4");

JButton btn5 = new JButton("5");

JButton btn6 = new JButton("6");

JButton btn7 = new JButton("7");

JButton btn8 = new JButton("8");

JButton btn9 = new JButton("9");

[Link](btn1); [Link](btn2); [Link](btn3);

[Link](btn4); [Link](btn5); [Link](btn6);

23
[Link](btn7); [Link](btn8); [Link](btn9);

[Link](new GridLayout());

[Link](300, 300);

[Link](true);

public static void main(String argvs[])

new GridLayoutExample();

} }

Output:

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow).
It is the default layout of the 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

Constructors of FlowLayout class

FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.

FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.

24
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor

FileName: [Link]

import [Link].*;

import [Link].*;

public class FlowLayoutExample

{ JFrame frameObj;

FlowLayoutExample()

frameObj = new JFrame();

JButton b1 = new JButton("1");

JButton b2 = new JButton("2");

JButton b3 = new JButton("3");

JButton b4 = new JButton("4");

JButton b5 = new JButton("5");

JButton b6 = new JButton("6");

JButton b7 = new JButton("7");

JButton b8 = new JButton("8");

JButton b9 = new JButton("9");

JButton b10 = new JButton("10");

[Link](b1); [Link](b2); [Link](b3); [Link](b4);

[Link](b5); [Link](b6); [Link](b7); [Link](b8);

[Link](b9); [Link](b10);

[Link](new FlowLayout());

[Link](300, 300);

[Link](true);

25
public static void main(String argvs[])

{ new FlowLayoutExample();

Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or horizontally. For this
purpose, the BoxLayout class provides four constants. They are as follows:

Note: The BoxLayout class is found in [Link] package.

Fields of BoxLayout Class

public static final int X_AXIS: Alignment of the components are horizontal from left to right.

public static final int Y_AXIS: Alignment of the components are vertical from top to bottom.

Constructor of BoxLayout class

BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given
axis.

Java CardLayout
The Java 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.

Constructors of CardLayout Class

CardLayout(): creates a card layout with zero horizontal and vertical gap.

CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

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.

26
Event Handling
Event: Change in the state of an object is known as event i.e. event describes the change in state of
source.
Events are generated as result of user interaction with the graphical user interface components.
For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
Types of Event: The events can be broadly classified into two categories:
1. Foreground Events - Those events which require the direct interaction of [Link] are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page etc.
2. Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.

Event Handling: Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
 This mechanism have the code which is known as event handler that is executed when an
event occurs.
 Steps involved in event handling:
 The User clicks the button and the event is generated.
 Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 the method is now get executed and returns.
 Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
Delegation Event Model
The Delegation Event Model has the following key participants namely:
1. Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
2. Listener - It is also known as event [Link] is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event an
then returns.
 The benefit of this approach is that the user interface logic is completely separated from the
logic that generates the event.
 The user interface element is able to delegate the processing of an event to the separate
piece of code.
 In this model ,Listener needs to be registered with the source object so that the listener can
receive the event notification.
 This is an efficient way of handling the event because the event notifications are sent only to
those listener that want to receive them.

27
 The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based
event model using AWT to resolve the event problems. It provides a convenient mechanism
to support complex Java programs.
Design Goals: The design goals of the event delegation model are as following:
 It is easy to learn and implement
 It supports a clean separation between application and GUI code.
 It provides robust event handling program code which is less error-prone (strong compile-
time checking)
 It is Flexible, can enable different types of application models for event flow and
propagation.
 It enables run-time discovery of both the component-generated events as well as observable
events.
 It provides support for the backward binary compatibility with the previous model.
Example Java Program to Implement the Event Deligation Model:
[Link]:
import [Link].*;
import [Link].*;
public class TestApp {
public void search() {
// For searching
[Link]("Searching...");
}
public void sort() {
// for sorting
[Link]("Sorting....");
}
static public void main(String args[]) {
TestApp app = new TestApp();
GUI gui = new GUI(app);
}
}
class Command implements ActionListener {
static final int SEARCH = 0;
static final int SORT = 1;
int id;
TestApp app;
public Command(int id, TestApp app) {
[Link] = id;
[Link] = app;
}
public void actionPerformed(ActionEvent e) {
switch(id) {
case SEARCH:
[Link]();
break;

28
case SORT:
[Link]();
break;
}
}
}
class GUI {
public GUI(TestApp app) {
Frame f = new Frame();
[Link](new FlowLayout());
Command searchCmd = new Command([Link], app);
Command sortCmd = new Command([Link], app);
Button b;
[Link](b = new Button("Search"));
[Link](searchCmd);
[Link](b = new Button("Sort"));
[Link](sortCmd);
List l;
[Link](l = new List());
[Link]("Alphabetical");
[Link]("Chronological");
[Link](sortCmd);
[Link]();
[Link]();
}
}
Output:

AWT Event Classes


The Event classes represent the event. Java provides us various Event.
EventObject class:
It is the root class from which all event state objects shall be derived. All Events are constructed with
a reference to the object, the source, that is logically deemed to be the object upon which the Event
in question initially occurred [Link] class is defined in [Link] package.
Class declaration: Following is the declaration for [Link] class:
public class EventObject
extends Object
implements Serializable

29
Class constructors
S.N. Constructor & Description

1 EventObject(Object source)
Constructs a prototypical Event.
Class methods
S.N. Method & Description

1 Object getSource()
The object on which the Event initially occurred.

2 String toString()
Returns a String representation of this EventObject.
Methods inherited: This class inherits methods from the following classes:
[Link]
AWT Event Classes:
Following is the list of commonly used event classes.
Sr. Control & Description
No.

1 AWTEvent
It is the root event class for all AWT events. This class and its subclasses
supercede the original [Link] class.

2 ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is
double clicked.

3 InputEvent
The InputEvent class is root event class for all component-level input events.

4 KeyEvent
On entering the character the Key event is generated.

5 MouseEvent
This event indicates a mouse action occurred in a component.

6 TextEvent
The object of this class represents the text events.

7 WindowEvent
The object of this class represents the change in state of a window.

8 AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable
objects.

30
9 ComponentEvent
The object of this class represents the change in state of a window.

10 ContainerEvent
The object of this class represents the change in state of a window.

11 MouseMotionEvent
The object of this class represents the change in state of a window.

12 PaintEvent
The object of this class represents the change in state of a window.

AWT Event Listeners

The Event listener represent the interfaces responsible to handle events.


Java provides us various Event listener classes but we will discuss those which are more frequently
used.
Every method of an event listener method has a single argument as an object which is subclass of
EventObject class.
For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent
derives from EventObject.
EventListner interface: It is a marker interface which every listener interface has to [Link] class
is defined in [Link] package.
Class declaration: Following is the declaration for [Link] interface:
public interface EventListener
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.
Sr. No. Control & Description

1 ActionListener
This interface is used for receiving the action events.

2 ComponentListener
This interface is used for receiving the component events.

3 ItemListener
This interface is used for receiving the item events.

4 KeyListener
This interface is used for receiving the key events.

5 MouseListener
This interface is used for receiving the mouse events.

6 TextListener
This interface is used for receiving the text events.

31
7 WindowListener
This interface is used for receiving the window events.

8 AdjustmentListener
This interface is used for receiving the adjusmtent events.

9 ContainerListener
This interface is used for receiving the container events.

10 MouseMotionListener
This interface is used for receiving the mouse motion events.

11 FocusListener
This interface is used for receiving the focus events.

Java MouseMotionListener Interface

The Java MouseMotionListener is notified whenever you move or drag mouse. It


is notified againstMouseEvent. The MouseMotionListener interface is found in
[Link] package. It has two methods.

Methods of MouseMotionListener interface

The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener Example

1. import [Link].*;
2. import [Link].*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
4. MouseMotionListenerExample(){
5. addMouse
MotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. [Link]([Link]);

32
14. [Link]([Link](),[Link](),20,20);
15. }
16. public void
mouseMoved(MouseEvent e) {}
17.

18. public static void main(String[] args) {


19. new MouseMotionListenerExample();
20. }
21. }

Output:

Java ItemListener Interface

The Java ItemListener is notified whenever you click on the checkbox. It is

notified against [Link] ItemListener interface is found in [Link]


package. It has only one method: itemStateChanged().

itemStateChanged() method

The itemStateChanged() method is invoked automatically whenever you click or


unclick on theregistered checkbox component.

1. public abstract void itemStateChanged(ItemEvent e);

Java ItemListener Example

1. import [Link].*;
2. import [Link].*;
3. public class ItemListenerExample implements ItemListener{
4. Checkbox checkBox1,checkBox2;
5. Label label;
6. ItemListenerExample(){
7. Frame f= new Frame("CheckBox Example");
8. label = new Label();
9. [Link]([Link]);
10. [Link](400,100);

33
11. checkBox1 = new Checkbox("C++");
12. [Link](100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. [Link](100,150, 50,50);
15. [Link](checkBox1); [Link](checkBox2); [Link](label);
16. [Link](this);
17. [Link]
temListener(this); 18.
[Link](400,4
00);
19. [Link](null);
20. [Link](true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if([Link]()==checkBox1)
24. [Link]("C++ Checkbox: "
25. + ([Link]()==1?"checked":"unchecked"));
26. if([Link]()==checkBox2)
27. [Link]("Java Checkbox: "
28. + ([Link]()==1?"checked":"unchecked"));
29. }
30. public static void main(String args[])

31. {
32. new ItemListenerExample();
33. }
34. }

Output:

Java KeyListener Interface

The Java KeyListener is notified whenever you change the state of key. It is
notified against [Link] KeyListener interface is found in [Link]
package. It has three methods.

34
Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:

1. public abstract void keyPressed(KeyEvent e);


2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);

Java WindowListener Interface

The Java WindowListener is notified whenever you change the state of


window. It is notified againstWindowEvent. The WindowListener interface is
found in [Link] package. It has three methods.

Methods of WindowListener interface

The signature of 7 methods found in WindowListener interface are given below:

1. public abstract void windowActivated(WindowEvent e);


2. public abstract void windowClosed(WindowEvent e);
3. public abstract void windowClosing(WindowEvent e);
4. public abstract void windowDeactivated(WindowEvent e);
5. public abstract void windowDeiconified(WindowEvent e);
6. public abstract void windowIconified(WindowEvent e);
7. public abstract void windowOpened(WindowEvent e);

35
Java Applet

Applet is a small java code which runs on java with the help of web browser.

Applet is a special type of program that is embedded in the webpage to generate the
dynamic content.

It runs inside the browser and works at client side.

Advantage of Applet:

 It works at client side so less response time.


 Secured
 It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet: Plugin is required at client browser to execute applet.

Hierarchy of Applet:

As displayed in the above diagram, Applet class extends Panel. Panel class
extends Container which is the subclass of Component.

Lifecycle of Java Applet:

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The [Link] class 4 life cycle methods and

36
[Link] class provides 1 life cycle methods for an applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

[Link] class: The Component class provides 1 life cycle method of


applet.

5. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.

Types of Applets in Java

A special type of Java program that runs in a Web browser is referred to as Applet.
It has less response time because it works on the client-side. It is much secured
executed by the browser under any of the platforms such as Windows, Linux and
Mac OS etc.

There are two types of applets that a web page can contain.

1. Local Applet
2. Remote Applet

1. Local Applet:

Local Applet is written on our own, and then we will embed it into web pages. Local
Applet is developed locally and stored in the local system. A web page doesn't need
the get the information from the internet when it finds the local Applet in the
system. It is specified or defined by the file name or pathname. There are two
attributes used in defining an applet, i.e., the codebase that specifies the path name
and code that defined the name of the file that contains Applet's code.

Syntax:

<applet codebase = "tictactoe" code = "[Link]" width = 120 height = 1


20> </applet>

Example: First, we will create a Local Applet for embedding in a web page. After
that, we will add that Local Applet to the web page.

[Link]
import [Link].*;

import [Link].*;

37
import [Link].*;

import [Link].*;

public class FaceApplet extends Applet

{ public void paint(Graphics g){

[Link]([Link]);

[Link]("Welcome", 50, 50);

[Link](20, 30, 20, 300);

} }

2. Remote Applet:

A remote applet is designed and developed by another developer. It is located or


available on a remote computer that is connected to the internet. In order to run the
applet stored in the remote computer, our system is connected to the internet then
we can download run it. In order to locate and load a remote applet, we must know
the applet's address on the web that is referred to as Uniform Recourse
Locator(URL).

Syntax:
<applet codebase = "[Link] code = "[Link]" width = 120
height =120>

</applet>

Difference Between Local Applet and Remote Applet

Local Applet Remote Applet

There is no need to define the We need to define the Applet's URL in


Applet's URL in Local Applet. Remote Applet.

Local Applet is available on our Remote Applet is not available on our


computer. computer.

In order to use it or access it, we In order to use it or access it on our


don't need Internet Connection. computer, we need an Internet Connection.

It is written on our own and then It was written by another developer.


embedded into the web pages.

38
We don't need to download it. It is available on a remote computer, so we
need to download it to our system.

Applet execution: There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file: To execute the applet by html file, create an
applet and compile it. After that create an html file and place the applet code in html
file. Now click the html file.

[Link]
import [Link];

import [Link];

public class First extends Applet{

public void paint(Graphics g){

[Link]("welcome",150,150);

} }

Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
[Link]
<html>

<body>

<applet code="[Link]" width="300" height="300">

</applet>

</body>

</html>

Simple example of Applet by appletviewer tool: To execute the applet by


appletviewer tool, create an applet that contains applet tag in comment and compile
it. After that run it by: appletviewer [Link]. Now Html file is not required but it is
for testing purpose only.

//[Link]
import [Link];

import [Link];

public class First extends Applet{

public void paint(Graphics g){

39
[Link]("welcome to applet",150,150);

} }

/* <applet code="[Link]" width="300" height="300">

</applet> */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac [Link]

c:\>appletviewer [Link]

Displaying Graphics in Applet

[Link] class provides many methods for graphics programming. Some


Commonly used methods of Graphics class given below:
public abstract void drawString(String str, int x, int y): is used to draw the specified
string.

public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.

public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.

public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.

public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.

public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).

public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is


used draw the specified image.

public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.

public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.

public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.

public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Example of Graphics in applet:


import [Link];

import [Link].*;

40
public class GraphicsDemo extends Applet{

public void paint(Graphics g){

[Link]([Link]);

[Link]("Welcome",50, 50);

[Link](20,30,20,300);

[Link](70,100,30,30);

[Link](170,100,30,30);

[Link](70,200,30,30);

[Link]([Link]);

[Link](170,200,30,30);

[Link](90,150,30,30,30,270);

[Link](270,150,30,30,0,180);

[Link]
<html>

<body>

<applet code="[Link]" width="300" height="300">

</applet>

</body>

</html>

41

You might also like