Java Unit-5
Java Unit-5
Java Unit-5
UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
Applets
Concepts of Applets
Applet is a special type of program that is embedded in the webpage to generate dynamic
content. It runs inside the browser and works on the client side.
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone
programs. Instead, they run within either a web browser or an applet viewer. were created
with the standard applet viewer, called appletviewer, provided by the JDK. But we can use
any applet viewer or browser we like. Execution of an applet does not begin at main( ).
Output to our applet’s window is not performed by System.out.println( ).Rather, in non-
Swing applets, the output is handled with various AWT methods, such as drawString( ),
which outputs a string to a specified X,Y location. Input is also handled differently than in a
console application.
To use an applet, it is specified in an HTMLfile. One way to do this is by using the APPLET
tag. The applet will be executed by a Java-enabled web browser when it encounters the
APPLET tag within the HTMLfile. To view and test an applet more conveniently, simply
include a comment at the head of your Java source code file that contains the APPLET tag.
You can test the compiled applet by starting the applet viewer with your Java source code file
specified as the target.
Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a window
that is 200 pixels wide and 60 pixels high.
Advantage of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• It is Secured
• It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.
Java Applet Features
• Java applet is a small and easy-to-write Java program.
• One can easily install Java applet along with various HTML documents.
• One needs a web browser (Java based) to use applets.
• Applet do not have access to the network or local disk and can only access
browser-specific services.
• It cannot perform system operations on local machines.
• Java applet cannot establish access to local system.
Meaning A Java Application also known as The Java applet works on the client
application program is a type of side, and runs on the browser and
program that independently makes use of another application
executes on the computer. program so that we can execute it.
Requirement Its execution starts with the main( ) It does not require the use of any
of main( ) method only. The use of the main( ) main() method. Java applet initializes
method is mandatory. through init( ) method.
Installation We need to install the Java Java applet does not need to be pre-
application first and obviously on installed.
the local computer.
Operation It performs read and write tasks on It cannot run the applications on any
a variety of files located on a local local computer.
computer.
File access It can easily access a file or data It cannot access the file or data found
available on a computer system or on any local system or computer.
device.
Security Java applications are pretty trusted, Java applets are less reliable. So, they
and thus, come with no security need to be safe.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html
file and place the applet code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome",150,150);
7. }
8. }
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Types of Applets
A special type of Java program that runs in a Web browser is referred to as Applet. It has less
response time because it works on the client-side. It is much secured executed by the browser
under any of the platforms such as Windows, Linux and Mac OS etc. There are two types of
applets that a web page can contain.
• Local Applets:
They are developed and stored locally, and therefore do not require an Internet
connection to be located because the directory is located on the local system.
Creating Applets
Example program:
import java.applet.*;
import java.awt.*;
/*<applet code="Apppletlifecycle.class" width=200 height=200>
</applet>*/
public class Apppletlifecycle extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
public void paint(Graphics g)
{
g.drawString("welcome to applet program",50,50);
}
}
Output:
To pass parameters to an applet in Java, you can use the param tag in the HTML file that
embeds the applet. The param tag takes two attributes: name and value. The name attribute
specifies the name of the parameter, and the value attribute specifies the value of the
parameter.We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Swing – Introduction
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API
and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Limitations of AWT:
1. Limited Customization: Compared to more modern GUI libraries like JavaFX, AWT
offers limited customization options for GUI components. It can be challenging to achieve
sophisticated visual designs without relying on platform-specific features.
2. Lack of Modern Features: As one of the earliest GUI libraries in Java, AWT lacks some
of the modern features found in later frameworks like JavaFX. For instance, it doesn’t
support hardware acceleration, which can impact graphical performance.
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.
In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal
with massive code.
o The extending and testing of application is easier.
Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components.
Swing provides a rich set of widgets and packages to make sophisticated GUI components for
Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java
GUI programing that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java simple GUI programming components
like button, textbox, etc., from the library and do not have to create the components from
scratch.
1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel
is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has
to be displayed. It is not a fully functioning window like the Frame.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look
and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager sets the layout manager for the component.
m)
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
A Java applet is a small program that is intended to be embedded within web pages and run in
the context of a web browser. JApplet is a specific class that extends Java applet and provides
support for Swing.
JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Nested Class
Fields
protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will
be forwarded to the contentPane.
Constructor Description
JFrame(String title) It creates a new, initially invisible Frame with the specified
title.
JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen device.
JFrame Example
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5. JButton b=new JButton("click");//creating instance of JButton
6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
7. f.add(b);//adding button in JFrame
8. f.setSize(400,500);//400 width and 500 height
9. f.setLayout(null);//using no layout managers
10. f.setVisible(true);//making the frame visible
11. }
12. }
Output:
The JComponent class is the base class of all Swing components except top-level containers.
Swing components whose names begin with "J" are descendants of the JComponent class.
For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog don't inherit
JComponent class because they are the child of top-level containers.
The JComponent class extends the Container class which itself extends Component. The
Container class has support for adding components to the container.
Output:
To add an icon to a button in Java Swing, you can use the Icon class. The Icon class allows
you to add an image to a button. Here is an example:
Icon icon = new ImageIcon("E:\editicon. PNG");
JButton button7 = new JButton(icon);
You can also add an icon to a frame in Java Swing. To do this, you can use the
setIconImage() method. The setIconImage() method takes an Image object as its
argument. Here is an example:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
frame.setIconImage(img);
You can also add an icon to a label in Java Swing. To do this, you can use the setIcon()
method. The setIcon() method takes an Icon object as its argument. Here is an example:
Icon icon = new ImageIcon("E:\editicon. PNG");
JLabel label7 = new JLabel(“Warning”);
Example program:
import javax.swing.*;
public Example() {
JFrame frame = new JFrame();
JLabel label = new JLabel(“Warning”);
JLabel
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.
Methods Description
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
Output:
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
JTextField Example
1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
Constructor Description
Methods Description
Output:
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Constructor Description
JCheckBox(String text, Creates a check box with text and specifies whether or not it
boolean selected) is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Methods Description
Output:
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
Constructor Description
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
Methods Description
Output:
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
Constructor Description
Methods Description
void removeAllItems() It is used to remove all the items from the list.
Output:
JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
Constructor Description
Output:
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
Constructor Purpose
JScrollPane(int, int)
JScrollPane(Component,
int, int)
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and
Component getCorner(String) must be one of the following constants
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5. public class JScrollPaneExample {
6. private static final long serialVersionUID = 1L;
7. private static void createAndShowGUI() {
8. // Create and set up the window.
9. final JFrame frame = new JFrame("Scroll Pane Example");
10. // Display the window.
11. frame.setSize(500, 500);
12. frame.setVisible(true);
13. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. // set flow layout for the frame
Output:
JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in the
tree. It inherits JComponent class.
Constructor Description
JTree(Object[] Creates a JTree with every element of the specified array as the child of a
value) new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the
root) root node.
Output:
JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Output: