0% found this document useful (0 votes)
11 views14 pages

Java Applets and AWT Overview

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)
11 views14 pages

Java Applets and AWT Overview

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

RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

UNIT V Applet: Applet class, Applet structure, Applet life cycle, sample Applet programs.
Event handling: event delegation model, sources of event, Event Listeners, adapter classes, inner
classes. AWT: introduction, components and containers, Button, Label, Checkbox, Radio
Buttons, List Boxes, Choice Boxes, Container class, Layouts, Menu and Scrollbar.

Applets
Applet is a java program that runs on the web browser to generate the dynamic content
and will work on the client side.

Points to be remembered
1. Applets are designed to be embedded within an HTML page
2. JVM is required to view an applet
3. Use import [Link].*; package
4. Web browser related code will write in the applet
5. Doesn’t use main() method and [Link]() method

Advantage of Applets
1. It works at client side so less response time
2. Secured
3. It can be executed by browsers running under many platforms, including Linux, Windows,
Mac Os etc.

Disadvantages of applets
1. The client browser requires a plugin to run the applet.
2. The mobile browser on IOS or Android does not run any Java applets. Desktop browsers have
dropped support for Java applets along with the rise of mobile operating systems.

Hierarchy of Applet

As displayed in the diagram, Applet class extends Panel.


Panel class extends Container which is the subclass of
Component.

1
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Applet implementation can be done in 2 ways

1. Using HTML file


2. Using appletviewer tool

1. Using 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.
Example: Applet Creation
import [Link].*;
import [Link].*;
public class AppletDemo extends Applet
{
public void paint(Graphics g)
{
[Link]("WELCOME”,150,150);
}
}
Save

C:\>[Link]

Compile

C:\>javac [Link]

Html file Creation

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

Save

[Link]

Execution using html

Double click on [Link]

2
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Output:

Note: If there is a plug-in for the browser then only the applet will be displayed.

2. Using 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].

Note: Html file is not required


Example
import [Link].*;
import [Link].*;

public class AppletDemo extends Applet


{
public void paint(Graphics g)
{
[Link]("welcome",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]

3
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Applet life cycle:

The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().These methods are invoked by the
browser to execute.

1. init()
The init() method is the first method to run that initializes the applet. It can be invoked only
once at the time of initialization.
2. start()
The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked.
It is invoked whenever the applet is Every time the browser is loaded, refreshed,
maximized, restored, or moving from one tab to another in the browser.
3. paint()
The paint() method belongs to the Graphics class in Java. It is used to draw shapes like
circle, square etc., in the applet.
It is executed after the start() method and when the browser or applet windows are
resized.
4. stop()
The stop() method stops the execution of the applet.
The stop () method is invoked whenever the applet is stopped, minimized, or moving from
one tab to another in the browser
4
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

5. destroy()
The destroy() method destroys the applet after its work is done.
It is invoked when the applet window is closed or the browser is closed.
It removes the applet object from memory and is executed only once.
We cannot start the applet once it is destroyed.
Note:
init(), start(), stop() and destroy() are available in [Link].*;
paint(Graphics g()) will be available in [Link].*;

As an applet starts working, the following methods are called in order:


 init()
 start()
 paint()
As an applet’s operation is about to come to an end, the following methods are called in order:
 stop()
 destroy()

Syntax
class AppletLifeCycle extends Applet {
public void init() {
// initialized objects
}
public void start() {
// code to start the applet
}
public void paint(Graphics graphics) {
// draw the shapes
}
public void stop() {
// code to stop the applet
}
public void destroy() {
// code to destroy the applet
}
}

5
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Example
import [Link].*;
import [Link].*;

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

public class AppletLifeCycle extends Applet


{
public void init()
{
setBackground([Link]);
[Link]("init() called");
}
public void start(){ [Link]("Start() called"); }
public void paint(Graphics g){ [Link]("Paint() called"); }
public void stop() { [Link]("Stop() Called"); }
public void destroy() { [Link]("Destroy() Called"); }
}
Output

6
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

AWT:
 AWT stands for Abstract Window Toolkit
 AWT is an API (Application Programming Interface) to develop GUI or window-based
applications
 AWT components are platform dependent so their look and feel changes according to OS
 AWT is heavyweight i.e. AWT components depends upon native code (current OS code) to
handle their functionality
 The [Link] package provides classes for AWT api such as TextField, Label, Button,
TextArea, RadioButton, CheckBox, Choice, List etc.

AWT Hierarchy:

The hierarchy of Java AWT classes are given below.

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 components are placed at their specific locations. Thus it
contains and controls the layout of components.

7
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Window
The window is the container that has 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.

Label:

 It is a passive control and is available in component class (awt package)


 Used to display text i.e., read only text
Constructors:
1. Label() : creates an empty label
2. Label(String str) : creates a label with specified text, LEFT justified
3. Label(String str, Alignment) : possible alignments are LEFT, RIGHT, CENTER
Methods:
1. getText(); : returns the name of label
2. setText(String str); : assigning a text / name to the label
 After this adding these components to container by add()
i.e., add(l1); add(l2); [Link]("REC");
Program
import [Link].*;
public class LabelDemo extends Frame{
LabelDemo()
{
Label l1=new Label();
Label l2=new Label("COLLEGE");
Label l3=new Label("Branch",[Link]);

[Link]("REC");

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


[Link](50, 150, 100, 30);
8
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

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

add(l1);
add(l2);
add(l3);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new LabelDemo();
}
}

Output

Button:
 Used to submit the form (form contains several components)
 If you click on the button then some action / event will be perform
Constructors:
1. Button() : creates an empty button i.e., button with no label displayed on it
2. Button(String str) : creates a button with label as given string
Methods:
1. getLabel() : returns the name of button
2. setLabel(String str) : assigning a name to the button
actionListener  actionPerformed()
 After this adding these components to container by add()
i.e., add(b1); add(b2); [Link](“SUBMIT”);

9
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Program
import [Link].*;
public class ButtonDemo
{
public static void main (String[] args)
{

// create instance of frame with the label


Frame f = new Frame("Button Demo");

// create instance of button with label


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

// set the position for the button in frame


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

// add button to the frame


[Link](b);

// set size, layout and visibility of frame


[Link](400,400);
[Link](null);
[Link](true);
}
}

Output

10
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

TextField:
 Used to create a single line text box ( Can enter only one line of text in the text box)
Constructors:
1. TextField() : creates a textbox with no text is displayed on the corresponding
box
2. TextField(int col) : creates a textbox with the given column size
3. TextField(String str) : creates a checkbox and filled with the given string in the box
4. TextField(String str, int col) : creates a checkbox and filled with the given string in the
specified column size box
Ex: user id and password text boxes
Methods:
1. getText() : returns the name of the corresponding textbox
2. setText(String str) : assigning a name to the textbox
3. setEchoChar(char) : assigning a name to the textbox
 After this adding these components to container by add();
i.e., add(t1); add(t2); add(t3);
Program
import [Link].*;
public class TextFieldDemo {
public static void main(String args[]) {

Frame f = new Frame("TextField Demo");

TextField t1 = new TextField("Welcome to Java.");


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

[Link](t1);

[Link](400,400);
[Link](null);
[Link](true);
}
}
Output

11
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

CheckboxGroup:
 Used to select single element (Creating Radio Buttons)
Constructor:
1. CheckboxGroup cbg=new CheckboxGroup();
Checkbox c=new Checkbox(string, cbg, boolean);
Ex: Gender  Male Female
Methods:
1. getLabel()  returns the label of the corresponding checkbox
2. setLabel(String str)  assigning a name to the checkbox
3. getState()  returns the state of the checkbox i.e., true / false (false, if it is
unchecked)
4. setState(boolean)  sets the state to the corresponding checkbox
 After this adding these components to container by add();
i.e., add(c1); add(c2); add(c3);
Program
import [Link].*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo()
{
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++",cbg, false);
[Link](100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java",cbg, true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckboxGroupDemo();
}
}

Output

12
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

Checkbox:
 Used to select multiple elements
 State of checkbox will be changed for each selection
Constructors:
1. Checkbox() : creates a checkbox with empty label i.e., checkbox with no label displayed on it
2. Checkbox(String str): creates a checkbox with label as given string
3. Checkbox(String str, Boolean on): //2nd parameter will select by default if boolean is on
4. Checkbox(String str, Checkbox cbg, Boolean on): create no. of checkboxes in a group
Ex: Hobbies  sports music reading

Methods:
1. getLabel() : returns the label associated with the corresponding checkbox
2. setLabel(String str) :assigning a name to the checkbox
3. getState() : returns the state of the checkbox i.e., true / false (false, if it is unchecked)
4. setState(boolean) : sets the state to the corresponding checkbox
 After this adding these components to container by add()
i.e., add(c1); add(c2); add(c3);
Program:
import [Link].*;
public class CheckboxDemo
{
CheckboxDemo()
{

Frame f = new Frame("Checkbox Example");


Checkbox checkbox1 = new Checkbox("C++");
[Link](100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
[Link](100, 150, 50, 50);

[Link](checkbox1);
13
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA

[Link](checkbox2);

[Link](400,400);
[Link](null);
[Link](true);
}

public static void main (String args[])


{
new CheckboxDemo();
}
}
Output

14

Common questions

Powered by AI

Java's AWT is platform-dependent because its components rely on native code from the host operating system for their functionality. This dependency means that the look and behavior of AWT components can vary across different platforms, impacting consistency in user interface experiences. Being heavyweight, the components interact directly with the native system, leading to differences in their appearance and how they handle system events .

The life cycle of an Applet includes five primary methods: init(), start(), paint(), stop(), and destroy(). The init() method initializes the applet and is called once. The start() method contains the actual code and is executed immediately after init(), as well as when the applet is revisited. The paint() method belongs to the Graphics class and is used to render shapes or text, executed after start() and whenever the window is resized or obscured. The stop() method halts the applet, triggered when the web page is minimized or switched. Finally, the destroy() method removes the applet, freeing resources, and is called once when the applet is closed .

In Java's AWT, the Frame is a top-level window commonly used in applications, featuring a title bar, borders, and can contain other components like buttons and text fields. The Panel acts as a container within a window, used to organize components without borders or menus. The Window is a general-purpose container without borders or menus, requiring a Frame, Dialog, or another Window for instantiation. These components together enable the creation and arrangement of user interface elements within Java applications .

Event handling in Java GUI applications is essential for managing user interactions, allowing a program to respond dynamically to user inputs such as clicks, key presses, and other actions. Java uses the event delegation model where event listeners are associated with GUI components to handle events. Event handling involves implementing relevant interfaces such as ActionListener for button clicks and registering listeners to components via the addActionListener() method. The process involves capturing the event, processing it, and executing defined actions in response, thus enabling interactive and responsive user interfaces .

AWT's heavyweight nature implies that components rely on the host OS to render UI elements, inheriting their native look and feel but also their limitations. This dependence means applications may not appear consistent across different platforms, posing a drawback for cross-platform Java applications. The reliance on native peers can also result in performance issues such as increased memory usage and slower rendering, impacting the scalability of applications. Developers might face challenges in achieving a unified user experience compared to lightweight toolkits like Swing .

Applets have several advantages including client-side execution which results in less response time and providing a secure way to run Java applications across many platforms such as Linux, Windows, and Mac OS. However, there are significant disadvantages; the client browser needs a plugin to run applets, and mobile browsers, including iOS and Android, do not support Java applets. Additionally, desktop browsers have reduced or dropped support for applets due to the proliferation of mobile OS .

Java applets can be executed using two primary methods: embedding within an HTML file or using the appletviewer tool. Executing with an HTML file involves creating an applet, compiling it, and then creating an HTML file with the applet code. Once the HTML file is launched in a browser, the applet runs (requires browser plugin). Using appletviewer involves writing the applet tag in comments within the Java file, compiling the applet, and executing it directly without needing an HTML file. This method is useful for testing without a browser .

In Java AWT, user interfaces can include Labels and Buttons as follows. A Label displays a non-editable text and is created using constructors such as Label(), Label(String), or Label(String, Alignment). Common methods include getText() to retrieve label text and setText(String) to modify it. Buttons are interactive components created with Button() or Button(String) to display text. Their methods include getLabel() and setLabel(String) to manage the display text. These components are typically added to a container like Frame with the add() method and positioned using layout managers or setBounds().

A Checkbox allows multiple selections from distinct options by multiple checkboxes remaining checked at the same time. Conversely, a CheckboxGroup creates radio buttons where only one option can remain selected, simulating exclusive choice among group members. The Checkbox uses constructors like Checkbox() or Checkbox(String), while CheckboxGroup involves creating an instance of CheckboxGroup and associating checkboxes with it. The state of a Checkbox is changed using setState(boolean), whereas the CheckboxGroup ensures only one selected checkbox at a time among its contained elements .

The paint() method in Java applets is significant for rendering the GUI components or graphics on the applet window. It is part of the AWT framework and belongs to the Graphics class. This method is called automatically after the applet's start() method or whenever the applet window requires redrawing, such as during resizing or exposure events. The paint() method takes a Graphics object as its argument, allowing operations like drawing strings, shapes, and images. It ensures that the applet's user interface is properly displayed and updated .

You might also like