0% found this document useful (0 votes)
3 views26 pages

Java Applet Unit IV

An applet is a Java program that runs within a web browser, enhancing web pages with dynamic content. It follows a specific lifecycle with methods like init(), start(), paint(), stop(), and destroy() for managing its execution. Applets can also accept parameters from HTML using the <param> tag and utilize the Graphics class for drawing and event handling to respond to user interactions.

Uploaded by

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

Java Applet Unit IV

An applet is a Java program that runs within a web browser, enhancing web pages with dynamic content. It follows a specific lifecycle with methods like init(), start(), paint(), stop(), and destroy() for managing its execution. Applets can also accept parameters from HTML using the <param> tag and utilize the Graphics class for drawing and event handling to respond to user interactions.

Uploaded by

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

What is Applet?

An applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works at client side.

An applet is embedded in an HTML page using the APPLET or OBJECT tag


and hosted on a web server.

Applets are used to make the website more dynamic and entertaining.

Important points :

1. All applets are sub-classes (either directly or indirectly)


of [Link] class.

2. Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool
called applet viewer.

3. In general, execution of an applet does not begin at main() method.

4. Output of an applet window is not performed by [Link](). Rather


it is handled with various AWT methods, such as drawString().

Life cycle of an applet :


It is important to understand the order in which the various methods shown in
the above image are called. When an applet begins, the following methods are
called, in this sequence:
1. init( )
2. start( )
3. paint( )

When an applet is terminated, the following sequence of method calls takes


place:
1. stop( )
2. destroy( )

Let’s look more closely at these methods.


1. init( ) : The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run time
of your applet.

2. start( ) : The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped. Note that init( ) is called once i.e. when the
first time an applet is loaded whereas start( ) is called each time an applet’s
HTML document is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( ).

3. paint( ) : The paint( ) method is called each time an AWT-based applet’s


output must be redrawn. This situation can occur for several reasons. For
example, the window in which the applet is running may be overwritten by
another window and then uncovered. Or the applet window may be minimized
and then restored.

paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called.

The paint( ) method has one parameter of type Graphics. This parameter will
contain the graphics context, which describes the graphics environment in
which the applet is running. This context is used whenever output to the applet
is required.

Note: This is the only method among all the method mention above, which is
parameterized. It’s prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.
Now the Question Arises:
Q. In the prototype of paint() method, we have created an object reference
without creating its object. But how is it possible to create object reference
without creating its object?

Ans. Whenever we pass object reference in arguments then the object will be
provided by its caller itself. In this case the caller of paint() method is browser,
so it will provide an object. The same thing happens when we create a very
basic program in normal Java programs. For Example:
public static void main(String []args){}
Here we have created an object reference without creating its object but it still
runs because it’s caller,i.e JVM will provide it with an object.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example.
When stop( ) is called, the applet is probably running. You should
use stop( ) to suspend threads that don’t need to run when the applet is not
visible. You can restart them when start( ) is called if the user returns to the
page.
5. destroy( ) : The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from memory. At
this point, you should free up any resources the applet may be using. The stop(
) method is always called before destroy( ).

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

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
[Link] ("Hello World", 25, 50);
}
}

Passing values through parameters in java applet

we will learn about passing parameters to applets using the param tag and retrieving the values
of parameters using getParameter method.

Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag.
Param Tag

The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value
of the parameter respectively. For example, the param tags for passing name and age
parameters looks as shown below:

<param name=”name” value=”Ramesh” />


<param name=”age” value=”25″ />

Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.

String getParameter(String param-name)


Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:

import [Link].*;
import [Link].*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
[Link]("Name is: " + n, 20, 20);
[Link]("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Graphics

Graphics is one of the most important features of Java. Java applets can be written to
draw lines, arcs, figures, images and text in different fonts and styles. Different colors
can also be incorporated in display.

Displaying Graphics in Applet

[Link] class provides many methods for graphics programming.

Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used


to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. 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.
4. public abstract void drawOval(int x, int y, int width, int
height): is used to draw oval with the specified width and height.
5. 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.
6. 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).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. 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.
10. public abstract void setColor(Color c): is used to set the
graphics current color to the specified color.
11. 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].*;
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>

Event Handling

Event handling in Java is the procedure that controls an event and performs appropriate action if
it occurs. The code or set of instructions used to implement it is known as the Event handler.

An event in a java program is generated upon clicking a button, typing in a textfield, checking a
checkbox or radio box, selecting an item in a drop down list.

Events in Java
Events in Java represent the change in the state of any object. Events occur when the user
interacts with the interface. Clicking a button, moving the mouse, typing a character, selecting an
item from a list, and scrolling the page are all examples of behaviors that cause an event to occur.

Types of Events in Java:


Foreground Events: These events necessitate the user's direct participation. They are produced as
a result of a user interacting with graphical components in a Graphical User Interface.

Background Events: Background events are those that require end-user interaction. Operating
system interrupts and hardware or software failures are examples of background events.

Components of Event Handling in Java


An Event Model is fundamentally composed of the three elements listed below:

 Events Handler
 Event Sources
 Event Listeners

In the subsequent sections, we will go over each one in-depth.

1. Event Handler

An event handler is a function or method that executes program statements in response to an


event. A software program that processes activities such as keystrokes and mouse movements is
what an event handler is. Event handlers in Web sites make Web content dynamic.

2. Event Sources

An object on which an event occurs is referred to as a source. The source is in charge of


informing the handler about the event that occurred. There are various sources like buttons,
checkboxes, lists, menu-item, choices, scrollbars, text components, windows, etc.

3. Event Listeners

When an event occurs, an object named an event listener is called. The listeners need two things:
first, they must be registered with a source; however, they can be registered with multiple
sources to receive event notifications.

Second, it must put in place the methods for receiving and processing notifications. A set of
interfaces defines the methods for dealing with events. The [Link] package contains the
following event classes and interfaces.

Event Classes and Listener Interfaces in Java


Event Classes Description Listener Interface

ActionEvent When a button is clicked or a list item is double-clicked, an ActionListener


Event Classes Description Listener Interface

ActionEvent is triggered.

MouseEvent This event indicates a mouse action occurred in a component MouseListener

The Key event is triggered when the character is entered


KeyEvent KeyListener
using the keyboard.

ItemEvent An event that indicates whether an item was selected or not. ItemListener

TextEvent when the value of a textarea or text field is changed TextListener

MouseWheelEvent generated when the mouse wheel is rotated MouseWheelListener

The object of this class represents the change in the state of


WindowEvent a window and are generated when the window is activated, WindowListener
deactivated, deiconified, iconified, opened or closed

when a component is hidden, moved, resized, or made


ComponentEvent ComponentEventListener
visible

ContainerEvent when a component is added or removed from a container ContainerListener

AdjustmentEvent when the scroll bar is manipulated AdjustmentListener

FocusEvent when a component gains or loses keyboard focus FocusListener

Event Handling in Java Example


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

public class LearningAWT {

public LearningAWT(){

// creating frame object


Frame frame = new Frame("Scaler topics, presents");
// creating button object and setting the bounds of it
// bounds are x,y cordinates in the container and
// width,hieght of the button object
Button mybtn = new Button("Click Me");
[Link](130,150,100,60);
[Link]([Link]);

// adding actionListner to the button


// that will change the UI
// once the button is clicked, as instructed

[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
float r = [Link]();
float g = [Link]();
float b = [Link]();

// choosing random background color for button after click


[Link](new Color(r,g,b));
r = [Link]();
g = [Link]();
b = [Link]();

// choosing random text color for button after click


[Link](new Color(r,g,b));

// updating button font


[Link](new Font("Arial", Font. BOLD, 18));
}
});

// locating the button inside the frame and


// setting the layout and size for the frame
[Link](mybtn);
[Link](300,300);
[Link](null);
[Link](true);

// adding windowlistner to the frame


// to make x button clickable.
[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link]();
}
});
}

public static void main(String[] args) {


LearningAWT f = new LearningAWT();

}
}

GUI

GUI, which stands for Graphical User Interface, is a user-friendly visual


experience builder for Java applications

GUI component classes consist of Button, Textfield, and Label. GUI container
classes consist of Frame, Panel, Dialog, and ScrollPane. Layout managers consist
of FlowLayout, BorderLayout, and Grid Layout. Custom graphics classes consist
of Graphics, Color, and Font.

Elements of GUI:

A GUI comprises an array of user interface elements. All these elements are displayed when a
user is interacting with an application and they are as follows:

1. Input commands such as buttons, check boxes, dropdown lists and text fields.

2. Informational components like banners, icons, labels or notification dialogs.

3. Navigational units like menus, sidebars and breadcrumbs.

Creating a GUI

The process of creating a GUI in Swing starts with creating a class that represents the main GUI.
An article of this class acts as a container which holds all the other components to be displayed.

In most of the projects, the main interface article is a frame, i.e., the JFrame class in [Link]
package. A frame is basically a window which is displayed whenever a user opens an application
on his/her computer. It has a title bar and buttons such as minimize, maximize and close along
with other features.

The JFrame class consists of simple constructors such as JFrame() and JFrame(String). The
JFrame() leaves the frame’s title bar empty, whereas the JFrame(String) places the title bar to a
specified text.
Apart from the title, the size of the frame can also be customized. It can be established by
incorporating the setSize(int, int) method by inserting the width and height desired for the frame.
The size of a frame is always designated in pixels.

For example, calling setSize(550,350) would create a frame that would be 550 pixels wide and
350 pixels tall.

Usually, frames are invisible at the time of their creation. However, a user can make them visible
by using the frame’s setVisible(boolean) method by using the word ‘true’ as an argument.

The following are the steps to create GUI in Java

STEP 1: The following code is to be copied into an editor

import [Link].*;

class gui{

public static void main(String args[]){

JFrame jframe = new JFrame("GUI Screen"); //create JFrame object

[Link](JFrame.EXIT_ON_CLOSE);

[Link](400,400); //set size of GUI screen

[Link](true);

}
STEP 2: Save and compile the code as mentioned above and then run it.

STEP 3: Adding buttons to the above frame. To create a component in Java, the user is required
to create an object of that component’s class. We have already understood the container class
JFrame.

One such component to implement is JButton. This class represents the clickable buttons. In any
application or program, buttons trigger user actions. Literally, every action begins with a click;
like to close an application, the user would click on the close button.

A swing can also be inserted, which can feature a text, a graphical icon or a combination of both.
A user can use the following constructors:

· JButton(String): This button is labelled with a specified text.

· JButton(Icon): This button is labelled with a graphical icon.

· JButton(String,Icon): This button is labelled with a combination of text and icon.


The following code is to be copied into an editor:
import [Link].*;

class gui{

public static void main(String args[]){

JFrame jframe = new JFrame("GUI Screen"); //create JFrame object

[Link](JFrame.EXIT_ON_CLOSE);

[Link](400,400); //set size of GUI screen

JButton pressButton = new JButton("Press"); //create JButton object

[Link]().add(pressButton);

[Link](true);

STEP 4: The above is to be executed. A big button will appear on the screen.

STEP 5: A user can add two buttons to the frame as well. Copy the code given below into an
editor.

import [Link].*;

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

JFrame jframe = new JFrame("GUI Screen");

[Link](JFrame.EXIT_ON_CLOSE);

[Link](400,400);

JButton firstButton = new JButton("First Button"); //create firstButton object

JButton secondButton = new JButton("Second Button"); //create secondButton object

[Link]().add(firstButton);

[Link]().add(secondButton);

[Link](true);

}
STEP 6: Save, compile and run the above code.

STEP 7: Unpredicted output = ? It means that the buttons are getting overlapped.

STEP 8: A user can create chat frames as well. Below is an example of the same:
Dialog Box

The main function of a dialog box is for an application or website to


retrieve some input from the user. That input can be an
acknowledgment that they have read a message or something they
enter into a text area.

A dialog box immediately captures a user’s attention. It’s a perfect


tool for collecting or displaying important information
Java is a diverse language that provides several classes to create dialog boxes. These classes
include JOptionPane, JDialog, and JFrame.

The JOptionPane Class


You can create a standard dialog box using one of several static methods belonging to the
JOptionPane class. These include:

showMessageDialog(), which relays a message to the user.


showConfirmDialog(), which asks a question that requires confirmation.
showInputDialog(), which prompts a user for input.
showOptionDialog(), which is a combination of the three other methods.

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:

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[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.

Java AWT Tutorial


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.
In [Link] package, the following components are available:

1. Containers: As the name suggests, this awt component is used to hold

other components.

Basically, there are the following different types of containers available in

[Link] package:
a. Window: This is a top-level container and an instance of a window class

that does not contain a border or title.

b. Frame: Frame is a Window class child and comprises the title bar, border

and menu bars. Therefore, the frame provides a resizable canvas and is the

most widely used container used for developing AWT-based applications.

Various components such as buttons, text fields, scrollbars etc., can be

accommodated inside the frame container.

Java Frame can be created in two ways:

 By Creating an object of Frame class.

 By making Frame class parent of our class.

o Dialog: Dialog is also a child class of window class, and it

provides support for the border as well as the title bar. In order

to use dialog as a container, it always needs an instance of frame

class associated with it.

o Panel: It is used for holding graphical user interface components

and does not provide support for the title bar, border or menu.

2. Button: This is used to create a button on the user interface with a

specified label. We can design code to execute some logic on the click event

of a button using listeners.


3. Text Fields: This component of java AWT creates a text box of a single

line to enter text data.

4. Label: This component of java AWT creates a multi-line descriptive string

that is shown on the graphical user interface.

5. Canvas: This generally signifies an area that allows you to draw shapes

on a graphical user interface.

6. Choice: This AWT component represents a pop-up menu having multiple

choices. The option which the user selects is displayed on top of the menu.

7. Scroll Bar: This is used for providing horizontal or vertical scrolling

feature on the GUI.

8. List: This component can hold a list of text items. This component allows

a user to choose one or more options from all available options in the list.

9. Checkbox: This component is used to create a checkbox of GUI whose

state can be either checked or unchecked.

Top 13 Components of Swing in Java


1. ImageIcon

The ImageIcon component creates an icon sized-image from


an image residing at the source URL.
ImageIcon homeIcon = new
ImageIcon("src/images/[Link]");

This returns an icon of a home button. The string parameter


is the path at which the source image is present.

2. JButton

JButton class is used to create a push-button on the UI. The


button can contain some display text or image. It generates
an event when clicked and double-clicked. A JButton can be
implemented in the application by calling one of its
constructors.

Example:

JButton okBtn = new JButton("Ok");

This constructor returns a button with text Ok on it.

JButton homeBtn = new JButton(homeIcon);

It returns a button with a homeIcon on it.

JButton btn2 = new JButton(homeIcon, "Home");

It returns a button with the home icon and text Home.


3. JLabel

JLabel class is used to render a read-only text label or images


on the UI. It does not generate any event.

Example:

JLabel textLbl = new JLabel("This is a text label.");

This constructor returns a label with text.

JLabel imgLabel = new JLabel(homeIcon);

It returns a label with a home icon.

4. JTextField

JTextField renders an editable single-line text box. A user can


input non-formatted text in the box. To initialize the text field,
call its constructor and pass an optional integer parameter to
it. This parameter sets the width of the box measured by the
number of columns. It does not limit the number of
characters that can be input in the box.

Example:

JTextField txtBox = new JTextField(20);


It renders a text box of 20 column width.

5. JTextArea

JTextArea class renders a multi-line text box. Similar to the


JTextField, a user can input non-formatted text in the field.
The constructor for JTextArea also expects two integer
parameters which define the height and width of the text-
area in columns. It does not restrict the number of characters
that the user can input in the text-area.

Example:

JTextArea txtArea = new JTextArea("This text is default text


for text area.", 5, 20);

The above code renders a multi-line text-area of height 5


rows and width 20 columns, with default text initialized in the
text-area.

6. JPasswordField

JPasswordField is a subclass of JTextField class. It renders a


text-box that masks the user input text with bullet points.
This is used for inserting passwords into the application.

Example:
JPasswordField pwdField = new JPasswordField(15);

var pwdValue = [Link]();

It returns a password field of 15 column width. The


getPassword method gets the value entered by the user.

7. JCheckBox

JCheckBox renders a check-box with a label. The check-box


has two states – on/off. When selected, the state is on and a
small tick is displayed in the box.

Example:

CheckBox chkBox = new JCheckBox("Show Help", true);

It returns a checkbox with the label Show Help. Notice the


second parameter in the constructor. It is a boolean value
that indicates the default state of the check-box. True means
the check-box is defaulted to on state.

8. JRadioButton

JRadioButton is used to render a group of radio buttons in the


UI. A user can select one choice from the group.

Example:
ButtonGroup radioGroup = new ButtonGroup();

JRadioButton rb1 = new JRadioButton("Easy", true);

JRadioButton rb2 = new JRadioButton("Medium");

JRadioButton rb3 = new JRadioButton("Hard");

[Link](rb1);

[Link](rb2);

[Link](rb3);

The above code creates a button group and three radio


button elements. All three elements are then added to the
group. This ensures that only one option out of the available
options in the group can be selected at a time. The default
selected option is set to Easy.

9. JList

JList component renders a scrollable list of elements. A user


can select a value or multiple values from the list. This select
behavior is defined in the code by the developer.

Example:

DefaultListItem cityList = new DefaultListItem();

[Link]("Mumbai"):

[Link]("London"):
[Link]("New York"):

[Link]("Sydney"):

[Link]("Tokyo"):

JList cities = new JList(cityList);

[Link](ListSelectionModel.SINGLE_SELECTIO
N);

The above code renders a list of cities with 5 items in the list.
The selection restriction is set to SINGLE_SELECTION. If
multiple selections is to be allowed, set the behavior to
MULTIPLE_INTERVAL_SELECTION.

10. JComboBox

JComboBox class is used to render a dropdown of the list of


options.

Example:

String[] cityStrings = { "Mumbai", "London", "New York",


"Sydney", "Tokyo" };

JComboBox cities = new JComboBox(cityList);

[Link](3);

The default selected option can be specified through the


setSelectedIndex method. The above code sets Sydney as
the default selected option.
11. JFileChooser

JFileChooser class renders a file selection utility. This


component lets a user select a file from the local system.

Example:

JFileChooser fileChooser = new JFileChooser();

JButton fileDialogBtn = new JButton("Select File");

[Link](new ActionListner(){

[Link]();

})

var selectedFile = [Link]();

The above code creates a file chooser dialog and attaches it


to the button. The button click would open the file chooser
dialog. The selected file is returned through the
getSelectedFile method.

12. JTabbedPane

JTabbedPane is another very useful component that lets the


user switch between tabs in an application. This is a highly
useful utility as it lets the user browse more content without
navigating to different pages.
Example:

JTabbedPane tabbedPane = new JTabbedPane();

[Link]("Tab 1", new JPanel());

[Link]("Tab 2", new JPanel());

The above code creates a two tabbed panel with headings


Tab 1 and Tab 2.

13. JSlider

JSlider component displays a slider which the user can drag


to change its value. The constructor takes three arguments –
minimum value, maximum value, and initial value.

Example:

JSlider volumeSlider = new JSlider(0, 100, 50);

var volumeLevel = [Link]();

The above code creates a slider from 0 to 100 with an initial


value set to 50. The value selected by the user is returned by
the getValue method.

You might also like