0% found this document useful (0 votes)
46 views39 pages

APPLET

The document discusses Java applets. An applet is a small program written in Java that runs in a web browser. Applets allow embedding interactive content like animations, games, and GUI components into web pages. Applets extend the Applet class and override methods like init(), start(), and paint() to control their lifecycle and display content. Common components that can be added to an applet include buttons, checkboxes, labels, text fields, and scrollbars. The document provides examples of creating simple applets using different layout managers like FlowLayout and BorderLayout.

Uploaded by

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

APPLET

The document discusses Java applets. An applet is a small program written in Java that runs in a web browser. Applets allow embedding interactive content like animations, games, and GUI components into web pages. Applets extend the Applet class and override methods like init(), start(), and paint() to control their lifecycle and display content. Common components that can be added to an applet include buttons, checkboxes, labels, text fields, and scrollbars. The document provides examples of creating simple applets using different layout managers like FlowLayout and BorderLayout.

Uploaded by

deepakebook
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

Java

APPLET
Containers and Components
 The job of a Container is to hold and display
Components

 Some common subclasses of Component are Button,


Checkbox, Label, Scrollbar, TextField, and
TextArea

 A Container is also a Component


 This allows Containers to be nested
 Some Container subclasses are Panel (and Applet),
Window, and Frame

2
An Applet is Panel is a Container

java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet

…so you can display things in an Applet

3
Applet
There are two kinds of Java programs, applications (also called
stand-alone programs) and Applets.

An Applet is a small Internet-based program that has the


Graphical User Interface (GUI), written in the Java programming
language.

Applets are designed to run inside a web browser or in applet


viewer to facilitate the user to animate the graphics, play sound,
and design the GUI components such as text box, button, and radio
button.

4
Applet class

The java.applet package is the smallest package in Java


API(Application Programming Interface). The Applet class is the
only class in the package. The Applet class has many methods
that are used to display images, play audio files etc but it has no
main() method.

init() : This method is used for whatever initializations are needed


for your applet.

5
start() : This method is automatically called after Java
calls the init method.

stop() : This method is automatically called when the user


moves off the page where the applet sits. If your applet
doesn't perform animation, play audio files, or perform
calculations in a thread, you don't usually need to use this
method.

destroy(): Java calls this method when the browser shuts


down.

6
Advantages of Applet

It is truly platform independent so there is no need of making


any changes in the code for different platform.

The same applet can work on "all" installed versions of Java at


the same time.

Applets can be used to provide dynamic user-interfaces and a


variety of graphical effects for web pages.

7
Applet Lifecycle
Every java Applet inherits a set of default behaviors from the
Applet class. As a result, when an applet is loaded it undergoes a
series of changes in its state. Following are the states in applets
lifecycle.

Born or Initialization state :

An applet begins its life when the web browser loads its classes and calls its
init() method. This method is called exactly once in Applets lifecycle and is used
to read applet parameters. Thus, in the init() method one should provide
initialization code such as the initialization of variables.
Eg. public void init()
{
//initialisation
}
8
Running State:

Once the initialization is complete, the web browser will call the
start() method in the applet. This method must called atleast
once in the Applets lifecycle as the start() method can also be
called if the Applet is in ―Stoped state. At this point the user
can begin interacting with the applet.
Eg. public void start()
{
//Code
}

9
Stopped State:
The web browser will call the Applets stop() method, if the user
moved to another web page while the applet was executing. So
that the applet can take a breather while the user goes off and
explores the web some more. The stop() method is called at least
once in Applets Lifecycle.
Eg. public void stop()
{
//Code
}

10
Display State :
Applet moves to the display state whenever it has to perform the
output operations on the screen. This happens immediately after
the applet enters into the running state. The paint() method is
called to accomplish this task.
Eg. public void paint(Graphics g)
{
//Display Statements
}

11
Dead State:

Finally, if the user decides to quit the web browser, the web
browser will free up system resources by killing the applet
before it closes. To do so, it will call the applets destroy()
method.
Eg. public void destroy()
{
// Code
}

12
13
Applets
 An application has a
public static void main(String args[ ]) method, but
an Applet usually does not
 An Applet's main method is in the Browser
 To write an Applet, you extend Applet and override
some of its methods
 The most important methods are init( ), start( ), and
paint(Graphics g)

14
To create an applet
 public class MyApplet extends Applet { … }
 this is the only way to make an Applet
 You can add components to the applet
 The best place to add components is in init( )
 You can paint directly on the applet, but…
 …it’s better to paint on a contained component
 Do all painting from paint(Graphics g)

15
Applet tag
The <applet....> tag included in the body section of HTML file supplies the
name of the applet to be loaded and tells the browser how much space the
applet requires.

The syntax for the standard Applet tag is as follows :

<applet[codebase=codebaseURL] code=‖Applet file‖


[ALT=‖alternative text]

Width=pixels height= pixels


[align= alignment]
>
[<param name=‖Attributename‖ value =‖Attribute value‖]
[<param name=‖Attributename‖ value =‖Attribute value‖]
........

</applet>
16
Some types of components
Label Button Checkbox

Choice Scrollbar

TextField List TextArea

Button

Checkbox CheckboxGroup
17
Creating components

Label lab = new Label ("Hi, Dave!");


Button but = new Button ("Click me!");
Checkbox toggle = new Checkbox ("toggle");
TextField txt =
new TextField ("Initial text.", 20);
Scrollbar scrolly = new Scrollbar
(Scrollbar.HORIZONTAL, initialValue,
bubbleSize, minValue, maxValue);

18
Adding components to the Applet
class MyApplet extends Applet {
public void init () {
add (lab); // same as this.add(lab)
add (but);
add (toggle);
add (txt);
add (scrolly);
...

19
Creating a Frame
 When you create an Applet, you get a Panel “for free”
 When you write a GUI for an application, you need to
create and use a Frame:
 Frame frame = new Frame();
 frame.setTitle("My Frame");
 frame.setSize(300, 200); // width, height
 ... add components ...
 frame.setVisible(true);
 Or:
 class MyClass extends Frame {
 ...
setTitle("My Frame"); // in some instance method
20
Arranging components
 Every Container has a layout manager
 The default layout for a Panel is FlowLayout
 An Applet is a Panel
 Therefore, the default layout for a Applet is FlowLayout
 You could set it explicitly with
setLayout (new FlowLayout( ));
 You could change it to some other layout manager

21
FlowLayout
 Use add(component); to add to a component when
using a FlowLayout
 Components are added left-to-right
 If no room, a new row is started
 Exact layout depends on size of Applet
 Components are made as small as possible
 FlowLayout is convenient but often ugly

22
Complete example: FlowLayout
import java.awt.*;
import java.applet.*;
public class FlowLayoutExample extends Applet
{
public void init () {
setLayout (new FlowLayout ()); // default
add (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));
}
}

23
BorderLayout
 At most five components can be
added
 If you want more components, add a
Panel, then add components to it.
 setLayout (new BorderLayout());

add (new Button("NORTH"), BorderLayout.NORTH);

24
BorderLayout with five Buttons

public void init() {


setLayout (new BorderLayout ());
add (new Button ("NORTH"), BorderLayout.NORTH);
add (new Button ("SOUTH"), BorderLayout.SOUTH);
add (new Button ("EAST"), BorderLayout.EAST);
add (new Button ("WEST"), BorderLayout.WEST);
add (new Button ("CENTER"), BorderLayout.CENTER);
}

25
Complete example: BorderLayout

import java.awt.*;
import java.applet.*;

public class BorderLayoutExample extends Applet {


public void init () {
setLayout (new BorderLayout());
add(new Button("One"), BorderLayout.NORTH);
add(new Button("Two"), BorderLayout.WEST);
add(new Button("Three"), BorderLayout.CENTER);
add(new Button("Four"), BorderLayout.EAST);
add(new Button("Five"), BorderLayout.SOUTH);
add(new Button("Six"), BorderLayout.SOUTH);
}
}

26
Using a Panel

Panel p = new Panel();


add (p, BorderLayout.SOUTH);
p.add (new Button ("Button 1"));
p.add (new Button ("Button 2"));

27
GridLayout

 The GridLayout manager


divides the container up into
a given number of rows and
columns:

new GridLayout(rows, columns)

 All sections of the grid are equally sized and as large as


possible

28
Complete example: GridLayout

import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends Applet {
public void init () {
setLayout(new GridLayout(2, 3));
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}
}

29
Making components active
 Most components already appear to do something--
buttons click, text appears
 To associate an action with a component, attach a
listener to it
 Components send events, listeners listen for events
 Different components may send different events, and
require different listeners

30
Listeners
 Listeners are interfaces, not classes
 class MyButtonListener implements
ActionListener {
 An interface is a group of methods that must be supplied
 When you say implements, you are promising to
supply those methods

31
Writing a Listener
 For a Button, you need an ActionListener

b1.addActionListener
(new MyButtonListener ( ));

 An ActionListener must have an


actionPerformed(ActionEvent) method

public void actionPerformed(ActionEvent e) {



}

32
MyButtonListener

public void init () {


...
b1.addActionListener (new MyButtonListener ());
}

class MyButtonListener implements ActionListener {


public void actionPerformed (ActionEvent e) {
showStatus ("Ouch!");
}
}
33
Listeners for TextFields
 An ActionListener listens for someone hitting the
Enter key
 An ActionListener requires this method:
public void actionPerformed (ActionEvent e)
 You can use getText( ) to get the text

 A TextListener listens for any and all keys


 A TextListener requires this method:
public void textValueChanged(TextEvent e)

34
AWT and Swing
 AWT Buttons vs. Swing JButtons:
 A Button is a Component
 A JButton is an AbstractButton, which is a JComponent, which is a
Container, which is a Component
 Containers:
 Swing uses AWT Containers
 AWT Frames vs. Swing JFrames:
 A Frame is a Window is a Container is a Component
 A JFrame is a Frame, etc.
 Layout managers:
 Swing uses the AWT layout managers, plus a couple of its own
 Listeners:
 Swing uses many of the AWT listeners, plus a couple of its own

 Bottom line: Not only is there a lot of similarity between AWT and Swing,
but Swing actually uses much of the AWT

35
Summary I: Building a GUI
 Create a container, such as Frame or Applet
 Choose a layout manager
 Create more complex layouts by adding Panels; each
Panel can have its own layout manager
 Create other components and add them to whichever
Panels you like

36
Summary II: Building a GUI
 For each active component, look up what kind of
Listeners it can have
 Create (implement) the Listeners
 often there is one Listener for each active component
 Active components can share the same Listener
 For each Listener you implement, supply the methods
that it requires
 For Applets, write the necessary HTML

37
Vocabulary
 AWT – The Abstract Window Toolkit provides basic graphics
tools (tools for putting information on the screen)
 Swing – A much better set of graphics tools
 Container – a graphic element that can hold other graphic
elements (and is itself a Component)
 Component – a graphic element (such as a Button or a
TextArea) provided by a graphics toolkit
 listener – A piece of code that is activated when a particular kind
of event occurs
 layout manager – An object whose job it is to arrange
Components in a Container

38
The End

39

Common questions

Powered by AI

Applets differ from standalone Java applications primarily in terms of their execution entry points. While standalone Java applications rely on a public static void main(String args[]) method to start execution, applets do not use a main method. Instead, applets depend on a web browser to manage their lifecycle, beginning with the init() method for initialization, followed by start(), which acts as the entry point when the applet becomes visible in the browser .

The <applet> tag is crucial for integrating Java applets into web pages because it specifies how the applet should be loaded and displayed within the browser. Attributes within the <applet> tag, such as code, width, and height, determine the Java class to load and the space the applet occupies. Optional attributes like codebase and align provide extra control over file directories and positioning, while <param> tags can pass additional parameter values to applets, influencing their behavior and customization. This tag ensures applets are displayed as intended and can interact correctly with other web elements .

The hierarchical structures of Java components and containers facilitate extensibility in user interface design by allowing developers to build complex interface layouts through nesting. Since containers like Panels and Windows are themselves components, they can hold other components or even other containers, promoting modular design. This nesting capability, combined with various layout managers, supports intricate interface designs wherein individual parts can be independently modified or extended without affecting the entire application. Such hierarchies enable flexible, scalable interfaces adaptable to evolving requirements and user needs .

In the applet lifecycle, the init(), start(), and paint() methods serve distinct roles that orchestrate the applet's behavior. The init() method is called once at applet initialization to set up variables and components. The start() method executes immediately after init() and whenever the applet's page is revisited, allowing for actions like start animations or other operations requiring repeated execution. In comparison, the paint() method is responsible for rendering the applet's graphical output on the screen whenever the display state is reached; it can be called multiple times depending on user actions or visual updates. These methods together ensure the applet initializes correctly, maintains operations, and properly displays content .

The lifecycle of a Java applet greatly facilitates dynamic interaction on a webpage by utilizing a series of state changes that govern its behavior. Initially, the applet enters the initialization state with the init() method for setup tasks. It then moves to the running state via the start() method where users can interact with it. The stop() method temporarily halts the applet if it is not currently visible, but does not destroy it, allowing the applet to resume efficiently. Finally, the destroy() method cleans up when the applet is no longer needed. This cycle allows for efficient resource management and facilitates dynamic user interfaces with smooth transitions and interactions .

FlowLayout and BorderLayout are two layout managers used in Java applets, each with distinct advantages and limitations. FlowLayout positions components left to right and starts a new row if space is unavailable; it is simple to use but can result in non-intuitive and unattractive layouts if not spaced properly. BorderLayout divides the container into five regions (North, South, East, West, Center), allowing more structured layouts; however, only one component can be placed in each region, limiting complex arrangements unless additional nested panels are used .

The primary role of a container in Java applets is to hold and display components such as Buttons, Checkboxes, Labels, etc. A container is also a component itself, allowing for the nesting of containers within each other. This hierarchical structure supports complex user interface designs by enabling containers to manage the layout and organization of components within them .

Listeners enhance the functionality of components in Java applets by enabling them to respond to user interactions and events. By associating listeners with specific components, developers can define methods such as actionPerformed() to handle events like button clicks or text entry completions. This allows for dynamic responses and interactive applications, where each component can have a tailored reactive behavior, improving the overall user experience .

AWT and Swing are both Java libraries for graphical user interface (GUI) development but have important differences. AWT is Java's original platform-dependent GUI toolkit, providing basic components like windows and buttons with native look and feel. Swing extends AWT with a richer set of components, offering more sophisticated features and a pluggable look and feel independent of the underlying platform. Although Swing uses AWT's underlying infrastructure for components and layout managers, it offers more functionality, such as lightweight components and enhanced flexibility for creating modern GUI applications .

Creating a Frame for a GUI in Java applications involves explicitly defining a top-level window with properties like size and title, making it suitable for standalone applications with independent windows. In contrast, a Panel in applets serves as a basic container that automatically becomes part of the browser window when the applet renders. While the Frame acts as the main container for building applications, Panels are ideal for organizing and grouping components within applets, facilitating flexible layouts in a restricted browser environment .

You might also like