Unit 5_JAVA-APPLETS,ABSTARCT WINDOW TOOLKIT,SWING.pdf

SonaShaiju1 9 views 81 slides Oct 31, 2025
Slide 1
Slide 1 of 81
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81

About This Presentation

An Applet is a small Java program that runs inside a web browser and cannot run on its own; it is mainly used for simple interactive content on web pages. AWT (Abstract Window Toolkit) is Java’s basic GUI toolkit used to create windows, buttons, labels, and text fields, but its components depend o...


Slide Content

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 tag
❖Applets are used to make the website more dynamic and entertaining

❖All applets are sub-classes (either directly or indirectly)
of java.applet.Applet class.
❖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.

❖In general, execution of an applet does not begin at main() method.
❖Output of an applet window is not performed by System.out.println().
Rather it is handled with various AWT methods, such as drawString().

Life cycle of an applet : 

❖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( )

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.It is called each time to browser loads or refreshes.
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output
must be redrawn.
paint(Graphics g) - is used to paint the Applet.It is automatically called when the
applet needs to be displayed or refreshed.

4. stop( ) : The stop( ) method is called when a web browser leaves the
HTML document containing the applet—when it goes to another page

5. destroy( ) : The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from
memory

Method When it is called Purpose Do we need to use it?
init() When the applet is first
loaded
Used for initialization
(e.g., creating UI
components, setting
variables)
Usually required
start() When the applet starts
running or becomes
visible
Start animations, start
threads, etc.
Optional
paint(Graphics g) Whenever the applet
needs to be redrawn (first
display, resize, etc.)
Used to draw output on
the screen
Usually required
stop() When the applet is no
longer visible or the user
switches pages
Stop animations or
threads
Optional
destroy() When the applet is being
removed from memory
Release resources Optional

Simple Applet program
//First.java  
import java.applet.Applet;  
import java.awt.Graphics;  
public class First extends Applet{  
  public void paint(Graphics g){  
g.drawString("welcome to applet",150,150);  
}  
  }  
/* 
<applet code="First" width="300" height="300"> 
</applet> 
*/  

To execute the applet by appletviewer tool, write in command prompt:
C:/> Javac First.java
C:/> appletviewer First.java

Applet Display methods
❖Applets are displayed in a window and they use the AWT to perform
input and output functions.
❖ To output a string to an applet, use drawString( ), which is a member
of the Graphics class.
❖ Typically, it is called from within either update() or paint( ). It has the
following general form:
void drawString(String message, int x, int y)

Simple applet to change the color of the
foreground and background.
import java.awt.*; 

import java.applet.*; 

/* <applet code="Applet_Prog" width=500 height=550> </applet>*/

public class Applet_Prog extends Applet 

{ 

public void paint (Graphics g) 

{ 

setBackground(Color.BLUE); 

setForeground(Color.RED); 

g.drawString("Using Colors in An Applet" , 100,250); 

} 

}

Repaint method()
❖The repaint () method causes the AWT runtime system to execute the
update () method of the Component class which clears the window
with the background color of the applet and then calls the paint ()
method.
❖For example: Suppose you want to display the current x and y
coordinates of the location where the mouse button is clicked in the
applet window.
❖Each time the mouse is clicked, this is possible with the use of the
repaint () method.
❖To sum up, the repaint() method is invoked to refresh the viewing area
i.e. you call it when you have new things to display.

❖import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="RepaintJavaExample.class" width="350" height="150">
</applet>*/
public class RepaintJavaExample extends Applet implements MouseListener
{
private int mouseX, mouseY;
private boolean mouseclicked = false;
public void init()
{
setBackground(Color.CYAN);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
mouseX = e.getX();
mouseY=e.getY();
mouseclicked = true;
repaint();
}

public void mouseEntered(MouseEvent e){}; 

public void mousePressed(MouseEvent e){}; 

public void mouseReleased(MouseEvent e){}; 

public void mouseExited(MouseEvent e){}; 

public void paint( Graphics g ) 

{ 

String str; 

g.setColor(Color.RED); 

if (mouseclicked) 

{ 

str = "X="+ mouseX + "," + "Y="+ mouseY ; 

g.drawString(str,mouseX,mouseY); 

mouseclicked = false; 

} 

} 

}

Abstract Window Toolkit
❑Java AWT is an API that contains large number of classes and methods to
create and manage graphical user interface ( GUI ) applications.
❑The AWT was designed to provide a common set of tools for GUI design
that could work on a variety of platforms.
❑AWT was Java’s first GUI Framework.
❑AWT is the foundation upon which Swing is made i.e Swing is a improved
GUI API that extends the AWT.

AWT
❑Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
❑AWT is heavyweight i.e. its components are using the resources of underlying
operating system (OS)
❑Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
❑The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

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,
text fields, 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.

Types of containers:
There are four types of containers in Java AWT:
❑Window:A basic top-level window with no borders or title bar by default.
❑Frame:A complete main window that has a title bar, borders, and buttons
❑Panel:A container used inside a window or frame to hold and organize
components.
❑Dialog:A small pop-up window that appears on top of a frame.
Used to show messages or get user input.

Types of containers:
❑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.

Types of containers:
❑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.
❑ Frame is a subclass of Window and have resizing canvas.

Types of containers:
❑The Dialog control
❑The Dialog control represents a top level window with a border and a title used to take
some form of input from the user.
❑It inherits the Window class.
❑Unlike Frame, it doesn't have maximize and minimize buttons.

❑Frame and Dialog both inherits Window class.
❑Frame has maximize and minimize buttons but Dialog doesn't have.

Creating a Frame
There are two ways to create a Frame. They are,
❑By Instantiating Frame class
❑By extending Frame class

Points to Remember:

❑While creating a frame (either by instantiating or extending Frame class),
Following two attributes are must for visibility of the frame:
•setSize(int width, int height);
•setVisible(true);
❑When you create other components like Buttons, TextFields, etc. Then you need
to add it to the frame by using the method - add(Component's Object);
❑You can add the following method also for resizing the frame
- setResizable(true);

By Instantiating Frame class

By extending Frame class

By extending Frame class

Understanding Layout Managers
❑The layout manager automatically positions all the components
within the container. If we do not use layout manager then also the
components are positioned by the default layout manager.
❑ Each Container object has a layout manager associated with it.
❑ A layout manager is an instance of any class that implements the
LayoutManagerinterface.

Understanding Layout Managers
❑The layout manager is set by the setLayout( ) method.
❑ If no call to setLayout( ) is made,then the default layout manager is used.
❑Whenever a container is resized (or sized for the first time), the layout
manager is used to position each of the components within it.
❑The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)

FlowLayout
❑It is the default layout manager.
❑FlowLayout implements a simple layout style, which is similar to how words flow in a text editor.
❑FlowLayout.LEFT
❑FlowLayout.CENTER
❑FlowLayout.RIGHT
❑FlowLayout.LEADING
❑FlowLayout.TRAILING
❑These values specify left, center, right, leading edge, and trailing edge alignment, respectively

BorderLayout
❑The BorderLayout class implements a common layout style for top-level windows.
❑It has four narrow, fixed-width components at the edges and one large area in the center.
❑ The four sides are referred to as north, south, east, and west. The middle area is called the center.
BorderLayout defines the following constants that specify the regions:
❑BorderLayout.CENTER
❑BorderLayout.SOUTH
❑BorderLayout.EAST
❑BorderLayout.WEST
❑BorderLayout.NORTH

AWT Control Fundamentals
❑The AWT supports the following types of controls:
❑These controls are subclasses of Component.
•Labels
•Buttons
•Check boxes
•Check box groups
•Choice control
•Lists
•Scroll bar
•Text field
•Text area

Adding and Removing Controls
❑In order to include a control in a window, we must add it to the
window.
❑ So, we must first create an instance of the desired control and then
add it to a window by calling add( ), which is defined by Container.
❑Component add(Component compObj)

Adding and Removing Controls
❑Once a control has been added, it will automatically be visible whenever its parent window is
displayed.
❑ Sometimes we will want to remove a control from a window when the control is no longer
needed.
❑ For doing this, call remove( ).
❑This method is also defined by Container.
❑It has this general form: void remove(Component obj) Here, obj is a reference to the control that
we want to remove.
❑We can remove all controls by calling removeAll( )

Label
❑A label is a user for placing text inside the container.
❑ A label is used only for inputting text.
❑The label does not imply that the text can be altered or it can be used
as a button which can be further worked upon.
Label n=new Label("Name:",Label.CENTER);

Label

Button
❑ This command generates a button in the User Interface.
❑Clicking on the button would move the command to another page or
another web server which is used to show several other outputs in the
user interface page.
a1=new Button("submit");
a2=new Button("cancel");

Button

Check Boxes
❑A check box is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not.
❑There is a label associated with each check box that describes what option the box
represents.
❑We change the state of a check box by clicking on it. Check boxes can be used
individually or as part of a group.
❑Check boxes are objects of the Checkbox class
❑Checkbox checkbox1 = new Checkbox("Hello World");

Check Boxes

Checkbox Group
❑It is possible to create a set of mutually exclusive check boxes in which one and only one check
box in the group can be checked at any one time.
❑These are often called radio buttons.
❑ For creating a set of mutually exclusive check boxes, we must first define the group to which they
will belong and then specify that group when we construct the check boxes.
❑Check box groups are objects of type CheckBoxGroup.
CheckboxGroup cb = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("Hello", cb, true);
checkBox1.setBounds (100,100, 50,50);

Checkbox Group

Managing Scroll Bars
❑Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or
vertically.
❑Each end has an arrow that you can click to move the current value of the
scroll bar one unit in the direction of the arrow.
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);

Managing Scroll Bars

TextField
❑The TextField class implements a single-line text-entry area, usually
called an edit control.
❑Text fields allow the user to enter strings and to edit the text using
the arrow keys, cut and paste keys, and mouse selections.
na=new TextField(“my name”);

TextField

TextArea
❑Sometimes a single line of text input is not enough for a given task.
To handle these situations, the AWT includes a simple multiline
editor called TextArea.
TextArea area=new TextArea("Welcome to the
universe");
area.setBounds(10,30, 300,300);

TextArea

Choice Controls
❑The Choice class is used to create a pop -up list of items from which the user may choose. Thus, a Choice
control is a form of menu.
❑ When inactive, a Choice component takes up only enough space to show the currently selected item. When
the user clicks on it, the whole list of choices pops up, and a new selection can be made.
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Subject 1");
c.add("Subject 2");
c.add("Subject 3");

Choice Controls

Lists
❑The List class provides a compact, multiple-choice, scrolling
selection list.
❑ Unlike the Choice object, which shows only the single selected item
in the menu, a List object can be constructed to show any number of
choices in the visible Window.
❑It can also be created to allow multiple selections.

Lists

Menu Bars and Menus

❑ A top-level window can have a menu bar associated with it.
❑A menu bar displays a list of top-level menu choices.
❑Each choice is associated with a drop-down menu.
❑ This concept is implemented in the AWT by the following classes:
MenuBar, Menu,and MenuItem.

Menu Bars and Menus

❑In general, a menu bar contains one or more Menu objects. Each Menu object contains a
list of MenuItem objects.
❑Each MenuItem object represents something that can be selected by the user.
❑Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be created.
❑It is also possible to include checkable menu items.
❑These are menu options of type CheckboxMenuItem and will have a check mark next to
them when they are selected.

Menu Bars and Menus

Menu Bars and Menus

❑Creating Menubar
MenuBar mb=new MenuBar();
❑Menu a creation
Menu mnu1=new Menu("BCA");
Menu mnu2=new Menu("BBA");

❑ sm1 and sm2 will be treated as submenus
Menu sm1=new Menu("Semester");
Menu sm2=new Menu("Year");
❑adding items and submenus to menu
mnu1.add(sm1);
mnu1.add(sm2);

❑//adding items to submenu
sm1.add(i1);
sm1.add(i2);
sm2.add(i3);
❑ //adding menu to menubar
mb.add(mnu1);
mb.add(mnu2);

❑Creating menu items
MenuItem i1,i2,i3;
i1=new MenuItem("I");
i2=new MenuItem("II");
i3=new MenuItem("2023");

Dialog Boxes
❑Dialog boxes are primarily used to obtain user input and are often child
windows of a top-level window.
❑ Dialog boxes don’t have menu bars, but in other respects, they function
like frame windows. (You can add controls to them, for example, in the
same way that you add controls to a frame window.)
❑When a modal dialog box is active, all input is directed to it until it is
closed.

Dialog Boxes
❑This means that you cannot access other parts of your program until
you have closed the dialog box.
❑ When a modeless dialog box is active, input focus can be directed to
another window in your program.
❑Thus, other parts of your program remain active and accessible. In
the AWT, dialog boxes are of type Dialog

Dialog Boxes

FileDialog
❑Java provides a built-in dialog box that lets the user specify a file.
❑ To create a file dialog box, instantiate an object of type FileDialog.
This causes a file dialog box to be displayed.
❑Usually, this is the standard file dialog box provided by the operating
system.

FileDialog

Handling Events by Extending AWT
Components
❑Handling events by extending AWT components.
❑The delegation event model was introduced in Event handling, and all of the
programs in this book so far have used that design. But Java also allows you to
handle events by subclassing AWT components.
❑Doing so allows you to handle events in much the same way as they were
handled under the original 1.0 version of Java. Of course, this technique is
discouraged, because it has the same disadvantages of the Java 1.0 event model,
the main one being inefficiency.

❑To extend an AWT component, you must call the enableEvents( )
method of Component. Its general form is shown here:

SWING

Swing
❑Java Swing is a popular and powerful Graphical User Interface (GUI)
toolkit that is used for developing desktop applications.
❑ It is a part of the Java Foundation Classes (JFC) and provides a rich set of
components and layout managers for creating a variety of GUIs.
❑Java Swing is platform-independent and can be used on any operating
system that supports Java.

Swing
❑It provides a set of lightweight components that are not only easy to use but also
customizable.
❑Some of the commonly used components in Swing are buttons, text fields, labels,
menus, and many more.
❑It also provides a robust event-handling mechanism that allows developers to
handle events generated by the graphical components.
❑Some of the commonly used layout managers in Java Swing are BorderLayout,
FlowLayout, GridLayout, CardLayout, and BoxLayout.

Features of Java Swing
❑Platform Independence: Platform independence is one of Java
Swing’s most remarkable features. It can run on any platform that
supports Java. Thus, Swing-based applications can run on Windows,
Mac, Linux, or any other Java-compatible operating system.
❑Lightweight Components: Java Swing provides a set of lightweight
components that are easy to use and customizable.

Features of Java Swing
❑Layout Managers: Java Swing provides a set of layout managers that can
be used to organize the graphical components in a GUI. These layout
managers enable developers to create flexible and responsive GUIs that
adapt to different screen sizes and resolutions.
❑Robust Event Handling Mechanism: Java Swing provides a robust event
handling mechanism that allows developers to handle events generated by
the graphical components. Developers can register event listeners to detect
and respond to user interactions with the GUI.

Features of Java Swing
❑Pluggable Look and Feel: Java Swing provides a pluggable look
and feels that allows developers to customize the appearance of the
GUI according to the user’s preferences. Developers can choose
from several pre-built looks and feel themes or create their own
custom themes.

The Model-View-Controller Architecture
❑Swing uses the model-view-controller architecture (MVC) as the
fundamental design behind each of its components. Essentially,
MVC breaks GUI components into three elements.
❑Each of these elements plays a crucial role in how the component
behaves.

Simmi S,ept of CS
Part Meaning What it Does
Model Data & Logic Stores data and performs
operations on the data.
View User Interface Displays data to the user
(screens, forms, buttons).
Controller Link between Model &
View
Takes user input, processes
it, and updates Model or
View.

Model = What to show (data)

View = How to show (display)

Controller = What to do (actions)

import javax.swing.*;
public class SimpleSwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing Program");
JButton button = new JButton("Click Me");
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the program when window is closed
frame.setVisible(true);
}
}
Tags