Unit V
Unit V
Unit V
Applets
Applet :
Applets are basically small java programs which can be easily transported
over the network from one computer to other. They are used in internet
applications, where these applets , embedded in an html page can be downloaded
from the server and run on the client, so as to do a specific kind of job.
To execute these applets on the client, the client must have either a
Applet Types:
1. conventional applets : They are directly evolved from Applet class. These
applets use Abstract Window ToolKit(AWT) to get GUI features.
2. Another type of applets are those which are based on Swing class for
drawing and display of graphics, JApplet.
Advantage of Applets
Drawback of Applet
o Plugin is required at client browser to execute applet.
BASIS FOR
APPLET APPLICATION
COMPARISON
main() method Do not use the main method Uses the main method for execution
Execution Cannot run independently Can run alone but require JRE.
require API's (Ex. Web API).
Installation Prior installation is not needed Requires prior explicit installation on the
local computer.
Read and write The files cannot be read and Applications are capable of performing
operation write on the local computer those operations to the files on the local
through applet. computer.
Communication with Cannot communicate with other Communication with other servers is
other servers servers. probably possible.
Restrictions Applets cannot access files Can access any data or file available on
BASIS FOR
APPLET APPLICATION
COMPARISON
Security Requires security for the system No security concerns are there.
as they are untrusted.
Applet class:
java.applet.Applet is the superclass of all the applets. Thus all the applets,
directly or indirectly use the methods of Applet belonging java.applet package.This
class provides all the necessary methods for starting ,stoping and manipulating
applets.
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Applet class Methods
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.
5. URL getDocumentBase(): Gets the URL of the document in which this applet is
embedded.
6. void resize(int width,int height):Resizes the applet according to the parameters ,
width and height.
7. String getAppletInfo():Returns string describing applet
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.
Apart from using the services of Applet class, an applet also uses the
services of Graphics class of the java.awt package. The applet class has
methods such as init(), start(),stop() and destroy() which are responsible for the
birth and behavior of an applet.
java Runtime systems does not call the main() method to start the execution
of an applet like in an application program rather it just loads the methods of
applet class which are responsible for starting, running , stopping and
manipulating an applet.
import java.applet.*;
//initialization
{
//suspends execution
Different states that an applet experiences between its objects creation and
object removal is known as Applet Life Cycle.
this method is called at the time of starting the execution. This is called only
once in the life cycle. This method initializes the Applet and it helps to initialize
variables and instantiate the objects and load the GUI of the applet. This is
invoked when the page containing the applet is loaded and places the applet in
new born state.
Its general form is:
public void init()
{
---
---
}
2.start() method:
The start() method executes immediately after the init() method. It starts the
execution of Applet. In this state the applet becomes active. It also executes
whenever the applet is restored, maximized or moving from one tab to another
tab in the browser.
public void start()
{
}
3.stop() method:
The stop() method stops the execution of the applet. It is invoked when the
Applet or the browser is minimized. The applet frequently comes to this state in
its life cycle and can go back to its active state.
4.paint() method:
This method helps to create Applet’s GUI such as a colored background and
writing. The paint() method executes after the execution of start() method and
whenever the applet or browser is resized.
5.destroy() method:
this method destroys the Applet and is also invoked only once when the
active browser page containing the applet is closed.
public void destroy()
{
}
when an applet is closed ,the method execution sequence is stop(), destroy()
<html>
<body>
<Applet code=”MyApplet.class” width=200 height=200>
</Applet>
</html>
2. create a java code for applet
MyApplet.java
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“MIC College”,150,150);
}
}
import java.applet.*;
import java.awt.*;
public class MyApplet1 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(30,200,300,10);
g.drawOval(50,50,100,100);
g.drawRect(100,100,100,100);
}
}
save : MyApplet1.java
<html>
<body>
<Applet code="MyApplet1.class" height=300
width=300>
</Applet>
</body>
</html>
save : MyApplet1.html
Run : appletviewer MyApplet1.html
Ex3: Java program to create different shapes and fill colors using applet
import java.applet.*;
import java.awt.*;
public class MyApplet2 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(30,200,300,10);
g.setColor(Color.blue);
g.drawOval(50,50,100,100);
g.setColor(Color.red);
g.drawRect(100,100,100,100);
g.fillRect(60,10,30,50);
}
}
save : MyApplet2.java
compile : javac MyApplet.java
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.
Remote Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("message");
g.drawString(str,50, 50);
}
}
Java Swing :
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.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Disadvantages of AWT:
The buttons of AWT does not support pictures.
It is heavyweight in nature.
Two very important components trees and tables are not present.
Extensibility is not possible as it is platform dependent.
MVC Architecture
MVC is an architectural pattern consisting of three parts: Model, View, Controller. Model: Handles data
logic. View: It displays the information from the model to the user. Controller: It controls the data flow into
a model object and updates the view whenever data changes
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Method Description
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
/*<Applet code=EventJApplet.class height=500 width=500>
</Applet>
*/
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
Constructor Description
JPanel Example
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PanelExample implements ActionListener{
JLabel l;
JButton b1,b2;
PanelExample()
{
b2=new JButton("Green");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
l=new JLabel();
l.setBounds(50,280,80,30);
l.setForeground(Color.orange);
panel.add(b1);
panel.add(b2);
panel.add(l);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
l.setText(s+" button clicked");
}
public static void main(String args[])
{
new PanelExample();
}
}
We can write the code of swing inside the main(), constructor or any other method.
import javax.swing.*;
public class Simple
{
JFrame f;
Simple()
{
f=new JFrame();//creating instance of JFrame
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
Ex :JButton example
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);
}
}
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
Methods Description
Ex :
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("MIC COLLEGE.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("KANCHIKACHERLA");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField:
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, int columns) Creates a new TextField initialized with the
specified text and columns.
Methods Description
Ex :
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to mic");
t1.setBounds(50,100, 200,30);
t2=new JTextField("java swings”);
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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, boolean Creates a check box with text and specifies
selected) whether or not it is initially selected.
Methods Description
import javax.swing.*;
SCheckBoxExample(){
checkBox1.setBounds(100,100, 50,50);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new SCheckBoxExample();
}
JList:
The object of JList class represents a list of text items. The list of text items can be
set up so that the user can choose either one item or multiple items. It inherits
JComponent class.
Constructor Description
Methods Description
Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the
scroll pane's client. The two int parameters, when present, set the vertical and
horizontal scroll bar policies (respectively).
JScrollPane(Component)
JScrollPane(int, int)
Useful Methods
Modifier Method Description
Void setColumnHeaderView(Component) It sets the column header for the scroll pane.
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 must be
one of the following constants defined in
Component getCorner(String)
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.
Void setViewportView(Component) Set the scroll pane's client.
The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using
JSplitPane.VERTICAL_SPLIT. When the user is resizing the components the
minimum size of the components is used to determine the maximum/minimum
position the components can be set to.
import java.awt.*;
import javax.swing.*;
public class JSplitPaneExample
{
JSplitPaneExample()
{
JFrame f= new JFrame("JSplitPane Example");
f.setSize(300, 300);
f.setVisible(true);
f.getContentPane().setLayout(new FlowLayout());
String[] option1 = { "A","B","C","D","E" };
JComboBox cb1 = new JComboBox(option1);
String[] option2 = {"1","2","3","4","5"};
JComboBox cb2 = new JComboBox(option2);
Panel panel1 = new Panel();
JButton b1=new JButton("B1");
panel1.add(cb1);
panel1.add(b1);
Panel panel2 = new Panel();
panel2.add(cb2);
//JSplitPane splitPane = new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
panel1, panel2);
f.getContentPane().add(splitPane);
}
public static void main(String[] args)
{
new JSplitPaneExample();
}
}
JTabbedPane
Constructor Description
p1.add(b1);
p2.add(b2);
p3.add(b3);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new TabbedPaneExample();
}
}
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.
Commonly used Constructors:
Constructor Description
JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a
new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays the
root node.
import javax.swing.*;
//import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.*;
JFrame f;
TreeExample()
f=new JFrame();
style.add(color);
style.add(font);
color.add(red);
color.add(blue);
color.add(black);
color.add(green);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
new TreeExample();
}
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.
Ex: Java program to create Tables
import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f=new JFrame();
String data[][]={ {"101","Arun", "20000"},
{"102","Deepak","80000"},
{"101","chaitanya","70000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java 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.
Constructor Description
JDialog(Frame owner, String title, It is used to create a dialog with the specified
boolean modal) title, owner Frame and modality.
Ex : Java program to create Dialog box
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample implements ActionListener
{
JDialog d;
DialogExample() {
JFrame f= new JFrame();
JButton b = new JButton ("OK");
d = new JDialog(f , "Dialog Example", false);
d.setLayout( new FlowLayout() );
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(200,200);
d.setVisible(true);
b.addActionListener(this);
}
public void actionPerformed( ActionEvent e )
{
d.setVisible(false);
}
public static void main(String args[])
{
new DialogExample();
}
}
JList:
The object of JList class represents a list of text items. The list of text items can be set up so that the user
can choose either one item or multiple items. It inherits JComponent class.
import java.awt.*;
import javax.swing.*;
JFrame f;
JList li;
ListEx()
f = new JFrame("frame");
"Thursday","Friday","Saturday","Sunday"};
li.setSelectedIndex(2);
p.add(l);
l.setBounds(50,50,100,50);
l.setForeground(Color.red);
f.add(p);
p.add(li);
li.setBounds(60,60,100,100);
f.setSize(400,400);
f.show();
new ListEx();
FlowLayout
The FlowLayout arranges the components in a directional flow,
either from left to right or from right to left. Normally all components are
set to one row, according to the order of different components. If all
components can not be fit into one row, it will start a new row and fit the
rest in.
To construct a FlowLayout , three options could be chosen:
1.FlowLayout():
construct a new FlowLayout object with center alignment and horizontal
and vertical gap to be default size of 5 pixels.
FlowLayout(int align):
construct similar object with different settings on alignment
FlowLayout(int align, int hgap, int vgap):
construct similar object with different settings on alignment and gaps
between components.
For the constructor with the alignment settings, the possible values could
be: LEFT, RIGHT, CENTER, LEADING and TRAILING .
import javax.swing.*;
import java.awt.*
panel.setLayout(new FlowLayout());
panel.add(jb1);
panel.add(jb2);
panel.add(jb3);
frame.add(panel);
frame.pack();
frame.setVisible(true);
BorderLayout:
A BorderLayout lays out a container, arranging its components to fit
into five regions: NORTH, SOUTH, EAST, WEST and CENTER . For
each region, it may contain no more than one component. When adding
different components, you need to specify the orientation of it to be the one of
the five regions.
CardLayout
For CardLayout , it treats the components as a stack and every time, what
you can see is only one component. That’s why it’s called CardLayout .
To demonstrate how to use CardLayout , three buttons have been
constructed. We can click the button and get the next button, then click it again,
getting the next one.
public CardLayoutExample() {
getContentPane().setLayout(new CardLayout(40, 30));
jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);
add(jb1);
add(jb2);
add(jb3);
setVisible(true);
setSize(300,300);
}
// Action listener
public void actionPerformed(ActionEvent e) {
card.next(c);
}
GridLayout
The GridLayout manager is used to lay out the components in a rectangle grid, which has
been divided into equal-sized rectangles and one component is placed in each rectangle. It can
constructed with following methods:
GridLayout(): construct a grid layout with one column per component in a single row.
GridLayout(int row, int col): construct a grid layout with specified numbers of rows and
columns.
GridLayout(int row, int col, int hgap, int vgap): construct a grid layout with specified
rows, columns and gaps between components.
With the following code, we can create a grid layout object with two rows, three columns.
Similarly, we can change the order of two and three to create three rows, two columns grid
layout object.
GridBagLayout
GridBagLayout is a more flexible layout manager, which allows the
components to be vertical, horizontal, without specifying the components to be the
same size. Each GridLayout object holds a dynamic rectangular grid of cells.
Each component is associated with an instance of GridBagConstraints .
The GridBagConstraints decides where the component to be displayed and
how the component should be positioned.