Java Unit V
Java Unit V
Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing window-
based applications.
Java Swing is lightweight and platform-independent that contains various components and container
classes.
It provides a wide range of components, such as buttons, text fields, and menus, that can be used to create
attractive and functional GUIs.
In Java Swing, there are several components like a scroll bar, button, text field, text area, checkbox, radio
button, etc. These components jointly form a GUI that offers a rich set of functionalities and allows high-
level customization.
Java Swing is a set of graphical user interface (GUI) components that are part of the Java platform.
Swing components are built on top of the Abstract Window Toolkit (AWT), but they provide a number of
advantages over AWT components. For example, Swing components are more lightweight and efficient,
and they are platform-independent.
To install the JDK, go to the Oracle website and download the latest version of the JDK for your operating
system. Once the JDK is installed, you can start creating Swing GUIs.
Platform Independent
Customizable
Extensible
Configurable
Lightweight
JFC is an abbreviation for Java Foundation classes, which encompass a group of features for
building Graphical User Interfaces(GUI) and adding rich graphical functionalities and interactivity to Java
applications.
Features of JFC
JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout, FlowLayout.
JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The component
which is added to the Frame, is refered as its Content.
JWindow : This is Swing's version of Window and hass descended directly from Window class.
Like Window it uses BorderLayout by default.
JLabel : JLabel descended from Jcomponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows an icon, string or both
associated with a button.
Creating a JFrame
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited
graphical interface. One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or peers. This means that the look and
feel of a component is defined by the platform, not by java. Because the AWT components use native code
resources, they are referred to as heavy weight.
The use of native peers led to several problems. First, because of variations between operating systems, a
component might look, or even act, differently on different platforms. This variability threatened java’s
philosophy: write once, run anywhere. Second, the look and feel of each component was fixed and could
not be changed. Third, the use of heavyweight components caused some frustrating restrictions.
MODEL-VIEW-CONTROLLER (MVC)
The Model-View-Controller (MVC) architecture in Java is a design pattern that provides a structured
approach for developing applications. It separates the application’s concerns into three main components:
the model, the view, and the controller. Each component has a specific role and responsibility within the
architecture.
Model:
The model represents the data and business logic of the application. It encapsulates the application’s data
and provides methods for accessing, manipulating, and updating that data. The model component is
independent of the user interface and focuses solely on the application’s functionality.
View:
The view is responsible for rendering the user interface and displaying the data to the user. It presents the
data from the model to the user in a visually appealing and understandable way. The view component does
not contain any business logic but instead relies on the model for data.
Controller:
The controller acts as an intermediary between the model and the view. It handles user input, processes
user actions, and updates the model or view accordingly. The controller interprets user actions and triggers
the appropriate methods in the model or view. It ensures the separation of concerns by keeping the view
and model independent of each other.
Java AWT is an API that contains large number of classes and methods to create and manage graphical
user interface ( GUI ) applications.
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
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 OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
The hierarchy of Java AWT classes are given below, all the classes are available in java.awt package.
Component class
Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the attributes
of visual component. A component object is responsible for remembering the current foreground and
background colors and the currently selected text font.
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.
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.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like
button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like
button, textfield etc.
AWT Example
import java.awt.*;
First()
}}
LAYOUT MANAGERS
The Layout managers allow us to control the arrangement of visual components in GUI forms by
controlling the size and position of components inside containers. There is a layout manager associated
with each Container object. A layout manager is an instance of a class that implements the LayoutManager
interface.
Layout managers are available for general use in several AWT and Swing classes:
BorderLayout
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
Border Layout
This arrangement will show the components along the container's border. The component can be
presented in five different places on this layout: North, South, East, West, and Center are the locations.
The center is the default region.
Example:
import java.awt.*;
// creating buttons
f1.setVisible (true);
}}
Box Layout
The BoxLayout places elements in a container either vertically in a single column or horizontally in a
single row. The components are assembled either top to bottom or left to right. The height of each
component will be the same and equal to the largest size component if the components are horizontally
aligned. The width of each component will be the same and equivalent to the greatest width component if
the components are vertically aligned.
X_Axis, Y_Axis, Line_Axis, and Page_Axis are the four constants that comprise the class. The horizontal
BoxLayout that the constant X_AXIS generates arranges each component from left to right. All
components are arranged vertically in a BoxLayout using the constant Y_AXIS, from top to bottom.
Example:
import java.awt.*;
import javax.swing.*;
Button buttons[];
public BoxLayoutDemo () {
add (buttons[i]);
setSize(500,500);
setVisible(true);
} }
Card Layout
The CardLayout arranges elements as a stack of cards. In a CardLayout, just the top card is visible.
CardLayout only shows one component at a time.
The top of the deck will be reserved for the first component to be inserted into the container. The card
components are presented horizontally or vertically, with a default gap of zero at the left, right, top, and
bottom edges.
There are 2 types of constructor in the Card Layout. They are as following:
1. CardLayout()
2. CardLayout(inthgap, intvgap)
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
CardLayoutc_Card;
JButton box1,box2,box3;
Container d;
CardDemo1()
d=getContentPane();
c_Card=new CardLayout(40,30);
d.setLayout(c_Card);
box1=new JButton("studytonight_1");
box2=new JButton("studytonight_2");
box3=new JButton("studytonight_3");
box1.addActionListener(this);
box2.addActionListener(this);
box3.addActionListener(this);
d.add("P",box1);
d.add("Q",box2);
d.add("R",box3);
c_Card.next(d);
obj.setSize(500,500);
obj.setVisible(true);
obj.setDefaultCloseOperation(EXIT_ON_CLOSE);
} }
Flow Layout
Like words on a page, it puts the elements in a container. It completely occupies the top line from top to
bottom and left to right. If the container is not broad enough to display all the components, they are
wrapped around the line in the order that they are inserted, with the first component appearing at the top
left. Component spacing can be adjusted both vertically and horizontally. The components may be
positioned to the left, center, or right.
The FlowLayout class defines the following five constants to represent the five various alignments:
LEFT
RIGHT
CENTER
LEADING
TRAILING
There are 3 types of constructor in the Flow Layout. They are as following:
1. FlowLayout()
2. FlowLayout(int align)
Example:
import java.awt.*;
import javax.swing.*;
JFrame frame1;
FlowDemo1(){
frame1=new JFrame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.add(box10);
frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
frame1.setSize(400,400);
frame1.setVisible(true);
new FlowDemo1();
} }
Gridbag Layout
It is a strong layout that organizes all the components into a grid of cells and keeps the object's
aspect ratio even when the container is modified. The size of the cells in this arrangement may vary. It
allocates components with a constant horizontal and vertical spacing. Using this feature, we can set a
default alignment for elements inside the columns or rows.
Constructors:
GridBagLayout(): A grid bag layout manager is made using the parameterless constructor.
Example:
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setLayout (gb);
//adding buttons
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0;
gc.gridy = 0;
gc.gridx = 1;
gc.gridy = 0;
f1.add (b2, gc);
gc.gridx = 2;
gc.gridy = 0;
gc.gridx = 0;
gc.gridy = 1;
gc.gridwidth = 3;
gc.ipady = 40;
gc.gridx = 2;
gc.gridy = 3;
f1.pack ();
f1.setVisible (true);
}}
Grid Layout
It arranges each element in a grid of cells that are all the same size, adding each element from left to right
and top to bottom. Each grid area will be the same size, and each cell can only hold one component. All
cells are automatically adjusted when the container is changed in size. As the elements are added, the order
in which they should be placed in a cell is decided.
1. GridLayout()
Example:
import java.awt.Button;
import java.awt.GridLayout;
import javax.swing.JFrame;
JFrame frame;
Button buttons[];
// constructor
GridLayoutDemo()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add (buttons[i]);
frame.setSize(300, 300);
frame.setVisible(true);
new GridLayoutDemo();
Event Handling
Event:
An event is an object that describes a state change in a source. It can be generated as a consequence of a
person interacting with the elements in a GUI. Some of the activities that cause events to be generated are
pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse.
Foreground Events - Those events which require the direct interaction of user. They 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.
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: 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.
The modern approach to handling events is predicated on the delegation event model, which defines
standard and consistent mechanisms to get and process events. Its concept is sort of simple: a source
generates an occasion and sends it to at least one or more listeners. In this scheme, the listener simply
waits until it receives an occasion. Once an occasion is received, the listener processes the event and then
returns.
The advantage of this design is that the application logic that processes events is cleanly separated from
the user interface logic that generates those events.
A user interface element is able to ―delegate‖ the processing of an event to a separate piece of code. In the
delegation event model, listeners must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that want to receive them.
In the delegation model, an event is an object that describes a state change in a source.
Among other causes, an event can be generated as a consequence of a person interacting with the elements
in a graphical user interface.
Some of the activities that cause events to be generated are pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
Event Sources
A source is an object that generates an event. Generally sources are components. Sources may generate
more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a specific type of
event. Each type of event has its own registration method. Here is the general form:
Here, Type is the name of the event, and el is a reference to the event listener. For example, the method
that registers a keyboard event listener is called addKeyListener( ).
A source must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this: public void removeTypeListener(TypeListener el )
Event Listeners
A listener is an object that is notified when an event occurs. It has two major requirements. First, it
must have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces, such as those found
in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved. Any object may receive and process one or both of
these events if it provides an implementation of this interface.
Sources of Events:
The classes that represent events are at the core of Java’s event handling mechanism. Widely used
Event classes are those defined by AWT and those defined by Swing.
The java.awt.event package provides many event classes and Listener interfaces for event
handling. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the super
class for all events. It‘s one constructor is shown here:
EventObject(Object src) - Here, src is the object that generates this event.
The package java.awt.event defines many types of events that are generated by various user interface
elements
The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK, CTRL_MASK, META_MASK (Ex. Escape), and
SHIFT_MASK.
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT The user clicked inside the scroll bar to increase its value.
TRACK The slider was dragged.
UNIT_DECREMENT The button at the end of the scroll bar was clicked to decrease its value.
UNIT_INCREMENT The button at the end of the scroll bar was clicked to increase its value.
The ComponentEvent Class:
A ContainerEvent is generated when a component is added to or removed from a container. There are two
types of container events. The ContainerEvent class defines constants that can be used to identify them:
COMPONENT_ADDED and COMPONENT_REMOVED.
A FocusEvent is generated when a component gains or loses input focus. These events are identified by the
integer constants FOCUS_GAINED and FOCUS_LOST.
The abstract class InputEvent is a subclass of ComponentEvent and is the super class for component input
events. Its subclasses are KeyEvent and MouseEvent.
A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are
identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event occurs only when a
character is generated.
There are eight types of mouse events. The MouseEvent class defines the following integer constants that
can be used to identify them:
Instances of this class describe text events. These are generated by text fields and text areas when
characters are entered by a user or program. TextEvent defines the integer constant
TEXT_VALUE_CHANGED.
The WindowEvent class defines integer constants that can be used to identify different types of events:
An event listener registers with an event source to receive notifications about the events of a particular
type. Various event listener interfaces defined in the java.awt.event package are given below:
INTERFACE DESCRIPTION
Defines the actionPerformed() method to receive and process action events.
ActionListener void actionPerformed(ActionEvent ae)
This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment
event occurs. Its general form is shown here:
This interface defines four methods that are invoked when a component is resized, moved, shown,
or hidden. Their general forms are shown here:
This interface defines two methods. When a component obtains keyboard focus, focusGained( )
is invoked.
This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes.
Its general form is shown here:
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked
when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has
been entered. For example, if a user presses and releases the A key, three events are generated in sequence:
key pressed, typed, and released. If a user presses and releases the HOME key, two key events are
generated in sequence: key pressed and released.
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called.
When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked
when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:
This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their
general forms are shown here:
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved.
Its general form is shown here:
This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or
text field. Its general form is shown here:
This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are
called when a window gains or loses input focus. Their general forms are shown here:
This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods
are invoked when a window is activated or deactivated, respectively. If a window is iconified, the
windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is
called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called,
respectively. The windowClosing( ) method is called when a window is being closed. The general forms of
these methods are
To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces
Mouse event occurs when a mouse related activity is performed on a component such as clicking,
dragging, pressing, moving or releasing a mouse etc. Objects representing mouse events are created from
MouseEvent class.
The following applet demonstrates the process. It displays the current coordinates of the mouse in the
applet’s status window. Each time a button is pressed, the word “Down” is displayed at the location of the
mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the
message “Mouse clicked” is displayed in the upperleft corner of the applet display area.
As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the
applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is
dragged. The two variables, mouseX and mouseY, store the location of the mouse when a mouse pressed,
released, or dragged event occurs. These coordinates are then used by paint( ) to display output at the point
of these occurrences.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
JLabel label;
MyMouse(){
addMouseListener(this);
label.setBounds(90,80,130,20);
add(label);
setSize(250,250);
setLayout(null);
setVisible(true);
label.setText("Clicked");
label.setText("Entered");
label.setText("Exited");
label.setText("Pressed");
}
label.setText("Released");
new MyMouse();
}}
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package.
It is a subclass of the abstract InputEvent class and is generated when the user presses or releases a key
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( )
event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( )
handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped( ) handler is invoked.
Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements KeyListener
{
String keystate="Hello PVPSIT"; String msg="";
MyFrame()
{
addKeyListener(this); addWindowListener(new MyWindow() );
}
public void keyPressed(KeyEvent ke)
{
keystate="Key Pressed"; msg+=ke.getKeyText( ke.getKeyCode()); repaint();
}
public void keyTyped(KeyEvent ke)
{
keystate="Key Typed"; repaint(); msg=msg+ke.getKeyChar();
}
public void keyReleased(KeyEvent ke)
{
keystate="Key Released"; repaint();
}
public void paint(Graphics g)
{
g.drawString(keystate,100,50); g.drawString(msg,100,100);
}
}
class KeyEventsExample
{
public static void main(String arg[])
{
MyFrame f=new MyFrame(); f.setTitle("Key Events Example"); f.setSize(500,300); f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}}
Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.
Action: What user does is known as action. Example, a click over button. Here, click is the action
performed by the user.
ADAPTER CLASSES:
Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in
certain situations. An adapter class provides an empty implementation of all methods in an event listener
interface. Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.
For example
MouseListener MouseAdapter
String msg;
WindowEx1(){
addWindowListener(new WA());
System.exit(0);
}}
class WindowAdapterEx
w.setVisible(true);
}}
Inner Classes:
Inner class is a class defined within another class, or even within an expression.
Listener classes are generally designed with just one purpose in mind: the creation of the listener object for
some GUI object (e.g., a button, window, checkbox, etc...). Given this relationship, separating the code for
the Listener class from the code for the class of the related GUI object seems to, in a certain sense, work
against the notion of the benefits of code encapsulation.
Fortunately, in Java, within the scope of one class, we are allowed to define one or more inner classes(or
nested classes). (Technically, the compiler turns an inner class into a regular class file named:
OuterClassName$InnerClassName.class.
Such inner classes can be defined inside the framing class, but outside its methods -- or it may even be
defined inside a method, and they can reference data and methods defined in the outer class in which it
nests
Example:
addWindowListener(new WA());
System.exit(0);
}}}
class WindowAdapterInner
w.setVisible(true);
}}
Anonymous Inner Classes:
Example:
addWindowListener(new WindowAdapter()
System.exit(0);
}});}}
class WindowAdapterAnonymous
w.setVisible(true);
}}
APPLETS:
An applet is a Java program that runs in a Web browser.(or) 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.
Applets are small Java applications that can be accessed on an Internet server, transported over Internet,
and can be automatically installed and run as apart of a web document.
After a user receives an applet, the applet can produce a graphical user interface. It has limited access to
resources so that it can run complex computations without introducing the risk of viruses or breaching data
integrity.
An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-
in of the Web browser or a separate runtime environment to run an applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an Applet.
Advantage of Applet:
•Secured
•It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os
etc.
Hierarchy of Applet :
As displayed in the diagram, Applet class extends Panel. Panel class extends Container, which is the
subclass of Component. Where Object class is base class for all the classes in java. JApplet class is
extension of Applet class.
init(): The init() method is the first method to execute when the applet is executed. Variable declaration
and initialization operations are performed in this method.
start(): The start() method contains the actual code of the applet that should run. The start() method
executes immediately after the init() method. It also executes whenever the applet is restored, maximized
or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The stop() method executes when the applet is
minimized or when moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is closed or when the tab containing the
webpage is closed. stop() method executes just before when destroy() method is invoked. The destroy()
method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet display area. The paint() method
executes after the execution of start() method and whenever the applet or browser is resized.
init()
start()
paint()
stop()
destroy()
The <applet> tag embeds a Java applet (mini Java applications) on the page. An applet is a program
written in the Java programming language that can be included in an HTML page, much in the same way
an image is included in a page.
Ex.
</applet>
To execute an Applet, FirstCreate an applet and compile it just like a simple java program.
First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirstextendsApplet
publicvoidpaint(Graphicsg)
g.drawString(“Welcome to Applet",50,150);
}}
Compile:
After that create an html file and place the applet code in html file
First.html
<html>
<body>
</applet>
</body>
</html>
Execute:
An Applet program is compiled in the same way as you have been compiling your console programs.
However there are two ways to run an applet.
Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes your applet in
a window
For executing an Applet in an web browser, create short HTML file in the same directory. Inside body tag
of the file, include the following code. (applet tag loads the Applet class)
To execute an Applet with an applet viewer, write short HTML file as discussed above. If name it
as run.htm, then the following command will run your applet program.
Code Execution: Applets could run arbitrary code on a user's computer, potentially leading to malware
infection or unauthorized access to system resources.
Outdated Java Versions: Users might have outdated Java installations with known vulnerabilities that
attackers could exploit.
Unsigned Applets: Even unsigned applets had limited access to system resources, raising the possibility
of malicious actions within the user's browser or system.
Certificate Problems: Signed applets were considered safer, but compromised or stolen certificates could
be used to distribute malicious applets.
Phishing: Malicious applets could be disguised as legitimate ones to trick users into running them.
Cross-Site Scripting (XSS): Applets could be exploited to facilitate cross-site scripting attacks,
compromising user data.
Browser Support: Major browsers phased out support for applets due to their security concerns.
Performance and Compatibility: Applets often suffered from slow loading times, performance issues,
and compatibility problems.
Small size
Applets are typically small, making them easy to download and embed in web pages.
Browser-based
Applets run inside a web browser, providing a convenient way to add interactivity and dynamic content to
web pages.
Restricted access to resources
Applets are run in a sandboxed environment, which restricts their access to system resources such as
memory, processing power, and storage.
Limited user interaction
Applets typically provide limited user interaction, usually through HTML controls or UI components
provided by the applet itself.
Deployment
Applets are typically embedded in HTML pages using the <applet> tag or the newer <object> tag.
Platform-independent
Applets are written in Java and can run on any platform that supports a Java Virtual Machine (JVM),
which makes them highly portable.
Security
Applets provide a high level of security and cannot access system resources or sensitive information.
Standalone
Applications are programs installed on a computer or other device and run independently of a web browser
or other software.
Access to Resources
Applications have access to system resources allowing them to perform complex tasks and manipulate
data.
User interaction
Applications provide user interaction through a GUI or CLI.
Deployment
They are generally distributed as executable files or installers. It can be downloaded and installed on a
computer or other device.
Platform-specific
They are usually developed for specific operating systems or hardware platforms.
Extensibility
Applications can be extended through plug-ins, add-ons, or other third-party software components.
DIFFERENCE BETWEEN APPLICATION AND APPLET
We can supply user defined parameter to an applet using tag . Param tag is used inside the applet
tag. Param tag has two attributes :
1. Name
2. Value
we will show you how to pass some parameters to an applet and how to read those parameters in an applet
to display their values in the output.
To pass the parameters to the Applet we need to use the param attribute of <applet> tag
To retrieve a parameter's value, we need to use the getParameter() method of Applet class.
import java.applet.Applet;
java.awt.Graphics;
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}}
<html>
<body>
</applet>
</body>
</html>
Output:
Welcome to Applet
Repaint() Method:
The paint() method is called by the JVM implicitly in two circumstances. One is when the first time frame
is created and displayed. The other is when the frame is resized (by dragging the frame border with mouse)
by the user. If the programmer would like to call the paint() method in the middle of the coding, he is
permitted to call repaint() method. He is not permitted to call paint() method directly (Java repaint() Call
paint()). This method again call the paint method in the program. So the graphics get repaint again. The
second case, when paint() calls are generated is when the program calls repaint() or update().
The repaint() method is the one invoked by a program to do drawing. Their are 4 versions of this method
but the one with no arguments is usually used. Drawing via repaint() most often takes place in response to
user input.
repaint() does not invoke paint() directly. It schedules a call to an intermediate method, update(). Finally,
update() calls paint() (unless you override update).
Update() Method
The update() method job is to erase the earlier drawings on the frame. On the cleared surface, the paint()
method draws a fresh with the latest graphics. If the programmer is allowed to call paint() method directly,
there is every possibility that he may forget to call the update() method explicitly. To avoid this and to
make Java as a robust language, the designers do not allow to call paint() directly.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
private Vector v;
public PaintRepaintTest()
v = new Vector();
setBackground(Color.white);
addMouseListener(this);
super.paint(g);
g.setColor(Color.black);
while(enumeration.hasMoreElements()) {
Point p = (Point)(enumeration.nextElement());
}}
public void mousePressed(MouseEvent me) {
v.add(me.getPoint());
frame.getContentPane().add(new PaintRepaintTest());
frame.setTitle("PaintRepaint Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(375, 250);
frame.setVisible(true);
}}
In the above program, if we click on the screen able to draw squares. In the mousePressed() method, we
can call the repaint() method.
Swing components
Swing provides a wide range of components that can be used to create GUIs. Swing Framework contains a
large set of components which provide rich functionalities and allow high level of customization. All these
components are lightweight components. They all are derived from JComponent class.Some of the most
commonly used components include:
Buttons
Text fields
Labels
Menus
Panels
Layout managers
JButton
JButton class provides functionality of a button. The button can include some display text or
images. It yields an event when clicked and double-clicked. JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
It allows a button to be created using icon, a string or both. JButton supports ActionEvent. When a button
is pressed an ActionEvent is generated.
Syntax:
EXAMPLE:
import javax.swing.*;
b.setBounds(85,110,105,50);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
} }
JLabel
JLabel is a Java Swing component. JLabel can show text, images, or a combination of the two. JLabel does not
respond to input events like mouse or keyboard focus.
Syntax:
Exаmple:
import javax.swing.*;
class Main
JLabel label1,label2;
label1=new JLabel("This is 1st Label");
label1.setBounds(50,50, 100,30);
label2.setBounds(50,100, 100,30);
myframe.add(label1); myframe.add(label2);
myframe.setSize(300,300);
myframe.setLayout(null);
myframe.setVisible(true); } }
JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text in the
box. We can initialize the text field by calling its constructor and passing an optional integer parameter.
This parameter sets the box width measured by the number of columns. Also, it does not limit the number
of characters that can be input into the box. It has three constructors:
Syntax:
Exаmple:
import javax.swing.*;
class Main
{
JTextField text1,text2;
text1.setBounds(50,100, 200,30);
text2.setBounds(50,150, 200,30);
myframe.add(text1); myframe.add(text2);
myframe.setSize(400,400);
myframe.setLayout(null);
myframe.setVisible(true);
} }
JCheckBox:
The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and off. On
selecting, the state is set to "on," and a small tick is displayed inside the box.
Syntax:
JCheckBox() - Initially, an unselected check box button is created with no text or icon.
JCheckBox(Action a) - This constructor creates a checkbox where the properties are taken from the
Action supplied.
JCheckBox(Icon icon) - This constructor initially creates an unselected checkbox with an icon.
JCheckBox(Icon icon, boolean selected) - It creates a checkbox with an icon that specifies if it is initially
selected or unselected.
JCheckBox(String text) - This constructor creates an unselected checkbox with the text.
JCheckBox(String text, boolean selected) - A checkbox with text is created and specifies if it is initially
selected or unselected.
JCheckBox(String text, Icon icon) - An unselected checkbox is created with the specified icon and text.
JCheckBox(String text, Icon icon, boolean selected) - A checkbox is created with text and icon and
specifies if it is initially selected or unselected.
Exаmple:
import java.awt.*;
import javax.swing.*;
static JFrame f;
f.setLayout(new FlowLayout());
p.add(c1);
p.add(c2);
f.add(p);
f.setSize(400, 400);
f.show();
}}
JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton class is
used to create a radio button in Frames.
Syntax:
Exаmple:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public Test()
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
new Test();
}}
JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is used to
create a combo box in Swing.
Syntax:
Exаmple:
import javax.swing.*;
JFrame f;
ComboBoxExample(){
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
new ComboBoxExample();
}}
JTabbedPane
The JTabbedPane is another beneficial component that lets the user switch between tabs in an application.
It is a handy utility as it allows users to browse more content without navigating to different pages.
Syntax:
The above code creates a two-tabbed panel with headings Tab_1 and Tab_2.
In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class. It is under package
javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class. The JMenuBar class is used
for displaying menubar on the frame. The JMenu Object is used to pull down the menu bar's components.
The JMenuItem Object is used for adding the labeled menu item.
JToggleButton
A JToggleButton is a button with two states. Selected and unselected are the two statuses. This
class is subclassed by the JRadioButton and JCheckBox classes. The toggle button toggles between being
pressed and unpressed when the user presses it. JToggleButton is a button that allows you to choose from a
list of options.
Constructors
JToggleButton(): Creates a toggle button with no text or image that is initially unselected.
JToggleButton(Action a): This method creates a toggle button with properties based on the Action.
JToggleButton(Icon icon): Creates a toggle button with the provided image but no text that is initially
unselected.
JToggleButton(Icon icon, boolean selected): Creates a toggle button with the provided image and
selection status, but no text.
JToggleButton(String text): Creates an unselected toggle button with the provided text.
JToggleButton(String text, boolean selected): Creates a toggle button with the supplied text and
selection status.
JToggleButton(String text, Icon icon): This method creates an unselected toggle button with the
provided text and image.
JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the supplied text,
image, and selection status.
JAVA JSCROLLPANE
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll
pane to display a large component or a component whose size can change dynamically.
Constructors
JScrollPane()
JScrollPane(Component)
JScrollPane(int, int)
JList
JList in Java is one of the Java Swing components. These components include buttons, sliders, list
boxes, checkboxes, etc. JList is defined in Java in the ‘java.swing’ package. JList is a component that
shows a list of objects and allows the user to choose one or more of them. JList is inherited from the
JComponent class. JComponent is an abstract class that serves as the foundation for all Swing
components.
Class Declaration
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-
null, model.
JDialog
The JDialog 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 Dialog class.
Constructors:
JDialog() - It is used to create a modeless dialog without a title and without a specified Frame
owner.
JDialog(Frame owner) - It is used to create a modeless dialog with specified Frame as its owner
and an empty title.
JDialog(Frame owner, String title, boolean modal) - It is used to create a dialog with the specified
title, owner Frame and modality.