Oops_java Unit 5 Notes
Oops_java Unit 5 Notes
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.
Advantages of Applets:
1. Execution of applets is easy in a Web browser and does not require any installation or
deployment procedure in realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not required
(but are required in applications).
Restrictions of Applets:
1. Applets are required separate compilation before opening in a browser.
2. In realtime environment, the bytecode of applet is to be downloaded from the server to the
client machine.
3. Applets are treated as untrusted (as they were developed by unknown people and placed on
unknown servers whose trustworthiness is not guaranteed) and for this reason they are not
allowed, as a security measure, to access any system resources like file system etc. available
on the client system.
4. Extra Code is required to communicate between applets using AppletContext
Hierarchy of Applet
Main() Method The execution of the Java application begins The Java applet initializes through the
with the main() method. The usage of the main() init(). It does not require the usage of any
is a prerequisite here. main() method.
Execution It cannot run alone, but it requires JRE for its It cannot run independently but requires
execution. APIs for its execution (Ex. APIs like Web
API).
Installation One needs to install a Java application priorly A Java applet does not require any prior
and explicitly on a local computer. installation.
Read and Write The Java applications are capable of performing A Java applet cannot perform these
Operations the read and write operations on various files applications on any local computer.
present in a local computer.
Restrictions These can easily access the file or data present in These cannot access the file or data
a computer system or device. available on any system or local
computers.
Security Java applications are pretty trusted, and thus, Java applets are not very trusted. Thus,
come with no security concerns. they require security.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class provides 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an applet.
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 240
java.applet.Applet class:
For creating any applet java.applet.Applet class must be inherited.
It provides 4 life cycle methods of applet.
o init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init() method
within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the applet
is maximized, restored, or moving from one tab to another in the browser. It is in an
inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to another
in the browser, the stop() method is invoked. When we go back to that page, the start()
method is invoked again.
o The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed or when the tab containing the webpage is closed. It removes
the applet object from memory and is executed only once. We cannot start the applet
once it is destroyed.
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.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
Program To Explain Applet Life Cycle
class TestAppletLifeCycle extends Applet {
public void init() {
// initialized objects
}
public void start() {
// code to start the applet
}
public void paint(Graphics graphics) {
// draw the shapes
}
public void stop() {
// code to stop the applet
}
public void destroy() {
// code to destroy the applet
}
}
...
[HTML Displayed in the absence of Java]
</APPLET>
Let’s take a look at each part now.
CODEBASE :
CODEBASE is an optional attribute that specifies the base URL of the applet
code, which is the directory that will be searched for the applet’s executable class file (specified
by the CODE tag). The HTML document’s URL directory is used as the CODEBASE if this
attribute is not specified. The CODEBASE does not have to be on the host from which the
HTML document was read.
CODE :
It is a required attribute that gives the name of the file containing your applet’s compiled .class
file. This file is relative to the code base URL of the applet, which is the directory that the
HTML file was in or the directory indicated by CODEBASE if set.
ALT :
The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser recognizes the APPLET tag but can’t currently run Java applets. This
is distinct from the alternate HTML you provide for browsers that don’t support applets.
NAME :NAME is an optional attribute used to specify a name for the applet instance.Applets
must be named in order for other applets on the same page to find them by name and
communicate with them. To obtain an applet by name, use getApplet( ), which is defined by
the AppletContext interface.
WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display
area.
ALIGN:
ALIGN is an optional attribute that specifies the alignment of the applet. The possible values:
LEFT, RIGHT,TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and
ABSBOTTOM.
These attributes are optional. VSPACE specifies the space, in pixels,bove and below the applet.
HSPACE specifies the space, in pixels, on each side of the applet.
Note:
APPLET tag should include only a CODE or an OBJECT attribute, but not both
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.
1. Local Applet
2. Remote Applet
Local Applet
• Local Applet is written on our own, and then we will embed it into web pages.
• Local Applet is developed locally and stored in the local system.
• A web page doesn't need the get the information from the internet when it finds the
local Applet in the system.
• It is specified or defined by the file name or pathname.
• There are two attributes used in defining an applet, i.e., the codebase that specifies the
path name and code that defined the name of the file that contains Applet's code.
<html>
<body>
<applet
code="First.class" width="300" height="300">
</applet>
</body>
</html>
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 244
Remote Applet
• A remote applet is designed and developed by another developer.
• It is located or available on a remote computer that is connected to the internet.
• In order to run the applet stored in the remote computer, our system is connected to the
internet then we can download run it.
• In order to locate and load a remote applet, we must know the applet's address on the
web that is referred to as Uniform Recourse Locator(URL).
<html>
<body>
<applet
codebase = "url link”
code="First.class" width="300" height="300">
</applet>
</body>
</html>
Difference between Local Applet and Remote Applet
The following table describes the key differences between Local applet and Remote
applet.
There is no need to define the Applet's We need to define the Applet's URL in Remote
URL in Local Applet. Applet.
Local Applet is available on our Remote Applet is not available on our computer.
computer.
In order to use it or access it, we don't In order to use it or access it on our computer,
need Internet Connection. we need an Internet Connection.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by
Java Plugin software that resides on the browser.
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 246
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code="First.class" width="300" height="300">*/
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
c:\>javac First.java
c:\>appletviewer First.java
Output:
Passing Parameters to Applets
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter().
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
/*
<applet code="UseParam.class" width="300" height="300">
<param name="Countryname" value="INDIA">
</applet>
*/
Output:
AWT Introduction
Computer users today expect to interact with their computers using a graphical user
interface (GUI). Java can be used to write GUI programs ranging from simple applets which
run on a Web page to sophisticated stand-alone applications.
•Applets.
A stand-alone application is a program that runs on its own, without depending on a Web
browser. You’ve been writing stand-alone applications all along. Any class that has a main()
routine defines a stand-alone application; running the program just means executing this main()
routine.
The user uses a mouse and keyboard to interact with GUI components such as windows, menus,
buttons, check boxes, text input boxes, scroll bars, and so on..
11.2 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 the look and
feel of a component is defined by the platform, not by java.
Because the AWT components use native code they are referred to as heavy weight.
Model :
View :
Controller:
➢ The controller connects with model and fetches the data and sends to the view layer.
➢ It acts as an interface between View and Model.
➢ It intercepts all the requests which are coming from the view layer.
➢ It receives the requests from the view layer and processes the requests and does the
necessary validation for the request.
➢ This requests is further sent to model layer for data processing, and once the request is
processed, it sends back to the controller with required information and displayed
accordingly by the view
The general architecture of MVC or 3-tier:
So let’s review: each Swing component contains a model and a UI delegate. The
model is responsible for maintaining information about the component’s state. The UI delegate
is responsible for maintaining information about how to draw the component on the screen. In
addition, the UI delegate (in conjunction with AWT) reacts to various events that propagate
through the component.
Note that the separation of the model and the UI delegate in the MVC design is
extremely advantageous. One unique aspect of the MVC architecture is the ability to tie
multiple views to a single model.
JApplet
We can even create applets based on the Swing package. In order to create such applets, we
must extend JApplet class of the swing package.
JApplet extends Applet class, hence all the features of Applet class are available in JApplet as
well, including JApplet's own Swing based features.
Swing applets provides an easier to use user interface than AWT applets.
Some important points :
➢ When we creat an AWT applet, we implement the paint(Graphics g) method to draw in
it but when we create a Swing applet, we implement paintComponent(Graphics g)
method to draw in it.
➢ For an applet class that extends Swing's JApplet class, the way elements like textfield,
buttons, checksboxes etc are added to this applet is performed by using a default layout
manager, i.e. BorderLayout.
➢ Swing applets use the same four lifecycle methods: init( ),start( ), stop( ), and destroy(
). Of course, you need override only those methods that are needed by your applet..
➢ Painting is accomplished differently in Swing than it is in the AWT,and a Swing
applet will not normally override the paint( ) method.when we create a Swing applet,
we implement paintComponent(Graphics g) method to draw in it.
Syntax:
To cause a component to be painted under program control, call repaint( ). It works in Swing
just as it does for the AWT. The repaint( ) method is defined by Component. Calling it causes
the system to call paint( ) as soon as it is possible to do so. In Swing the call to paint( ) results
in a call to paintComponent( ). Inside the overridden paintComponent( ), you will draw the
stored output
In this example , first, we have created a swing applet by extending JApplet class and we
have added a JPanel to it.Next, we have created a class B, which has extended JPanel class of
Swing package and have also implemented ActionListener interace to listen to the button
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 254
click event
import generated when buttons added to JPanel are clicked
java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="SwingAppletDemo.class" width="500" height="200">
</applet>
*/
public class SwingAppletDemo extends JApplet
{
public void init()
{
add(new B()); //Adding a JPanel to this Swing applet
}
}
class B extends JPanel implements ActionListener
{
JLabel jb;
JButton box1;
String str;
B( )
{
jb= new JLabel("click on button to display message");
box1 = new JButton("Box1");
str ="";
setLayout(new FlowLayout());
add(jb);
add(box1);
box1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Painting in Swing
Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will
not normally override the paint( ) method. when we create a Swing applet, we implement
paintComponent(Graphics g) method to draw in it.
Syntax:
To cause a component to be painted under program control, call repaint( ). It works in Swing
just as it does for the AWT. The repaint( ) method is defined by Component. Calling it causes
the system to call paint( ) as soon as it is possible to do so. In Swing the call to paint( ) results
in a call to paintComponent( ). Inside the overridden paintComponent( ), you will draw the
stored output
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 256
JLabels
The class ImageIcon is an implementation of the Icon interface that paints Icons from
Images.
JTextField
A JTextField is an area that the user can type one line of text into. It is a good way of getting
text input from the user.
Methods include:
Swing Buttons
Java Swing 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
➢ JButton
➢ JToggle Button
➢ JCheckBox
➢ JRadio Button
➢ JTabbed Pane
➢ JScroll Pane
➢ JList
➢ JComboBox
➢ Swing Menus
➢ Dialogs
14.2.1 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.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible
Constructor Description
It creates a button with no text
JButton()
and icon.
It creates a button with the
JButton(String s)
specified text.
It creates a button with the
JButton(Icon i)
specified icon object.
Example on JButton
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 260
JToggleButton constructors:
➢ JToggleButton(String str);
This creates a toggle button that contains the text passed in str.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo.class" width=200 height=80> </applet>
*/
public class JToggleButtonDemo extends JApplet implements ItemListener
{
JLabel jlab;
JToggleButton jtbn;
public void init()
{
setLayout(new FlowLayout());// Change to flow layout.
jlab = new JLabel("Button is off."); // Create a label
jtbn = new JToggleButton("On/Off");// Make a toggle button.
add(jtbn); // Add an item listener for the toggle button.
add(jlab);
jtbn.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
Output:
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.
Methods Description
It is used to get the AccessibleContext
AccessibleContext getAccessibleContext()
associated with this JCheckBox.
It returns a string representation of this
protected String paramString()
JCheckBox.
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 262
import javax.swing.*;
public class JCheckBoxDemo extends JApplet
{
/*
<applet code="JCheckBoxDemo.class" width="400" height="500">
</applet>
*/
public void init()
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("A");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("B", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
import javax.swing.*;
public class JRadioButtonDemo extends JApplet
{
/*<applet
Example code="JRadioButtonDemo.class"
program width=400 height=400></applet>*/
to demonstrate JRadioButton
JFrame f; JRadioButton r1,r2;
public void init()
{
f=new JFrame();
r1=new JRadioButton("A) Agree");
r2=new JRadioButton("B) DisAgree ");
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
Output:
}
}
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 264
Output:
Here, name is the name for the tab, and comp is the component that should be added to the tab.
Often, the component added to a tab is a JPanel that contains a group of related components.
This technique allows a tab to hold a set of components
In this example The first tab is titled “Seasons” and contains four buttons. Each button displays
the name of a Season. The second tab is titled “Gender” and contains three check boxes. Each
check box displays the name of a Gender. The third tab is titled “State” and contains one combo
box. This enables the user to select one of three flavors.
// Demonstrate JTabbedPane.
import javax.swing.*;
/*<applet code="JTabbedPaneDemo.class" width=400 height=100> </applet>*/
public class JTabbedPaneDemo extends JApplet {
public void init() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Season", new SeasonPanel());
jtp.addTab("Gender", new GenderPanel());
jtp.addTab("State", new StatePanel());
add(jtp);
}
}
// Make the panels that will be added to the tabbed pane.
class SeasonPanel extends JPanel {
public SeasonPanel() {
JButton b1 = new JButton("Summer");
add(b1);
JButton b2 = new JButton("Winter");
add(b2);
JButton b3 = new JButton("Rainy");
add(b3);
}
}
class GenderPanel extends JPanel {
public GenderPanel() {
JRadioButton cb1 = new JRadioButton("male");
add(cb1);
JRadioButton cb2 = new JRadioButton("female");
add(cb2);
JRadioButton cb3 = new JRadioButton("transgender");
add(cb3);
}
}
class StatePanel extends JPanel {
public StatePanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Telangan");
jcb.addItem("Andhrapradesh");
jcb.addItem("Tamilnadu");
add(jcb);
}
}
Output:
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 268
14.2.6 JScrollPane
another component. The component being scrolled can either be an individual component, such
as a table, or a group of components contained within another lightweight container, such as a
JPanel
JScrollPane(Component comp)
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/* <applet code="JScrollPaneDemo" width=300 height=250> </applet>*/
public class JScrollPaneDemo extends JApplet {
public void init()
{
// Add 400 buttons to a panel.
JPanel jp = new JPanel(); //step-1
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button "));
++b;
}}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp); //step-2
// Add the scroll pane to the content pane the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER); //step-3
}
}
Output:
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 270
Java 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.
JTree(Object[] Creates a JTree with every element of the specified array as the child
value) of a new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) displays the root node.
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data
import javax.swing.*;
JFrame f;
TableExample(){
f=new JFrame();
{"102","DEF","78"},
{"101","GHI","70"}};
String column[]={"ID","NAME","Markspercentage"};
jt.setBounds(30,40,200,300);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
new TableExample();
Output: