Java Unit5
Java Unit5
Java Applet
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 Applet
Drawback of Applet
Applications are just like a Java Applets are small Java programs that are
programs that can be execute designed to be included with the HTML
independently without using the web document. They require a Java-
web browser. enabled web browser for execution.
Applications can access all kinds Applets can only access the browser
of resources available on the specific services. They don’t have access to
system. the local system.
Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
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
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.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet",20,20);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag
in comment and compile it. After that run it by: appletviewer First.java. Now Html
file is not required but it is for testing purpose only.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Parameter in Applet
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>
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.
2.After that, we will add that Local Applet to the web page.
FaceApplet.java
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).
Specifying Remote applet
<applet
codebase = "http://www.jbrecnotes.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>
computer. computer.
o Heavyweight.
2. Lightweight Containers
JPanel:
1. JPanel(): Creates a new JPanel with a double buffer and a flow layout.
2. JPanel(boolean isDoubleBuffered): Creates a new JPanel with FlowLayout and
the specified buffering strategy.
3. JPanel(LayoutManager layout): Creates a new buffered JPanel with the
specified layout manager.
4. JPanel(LayoutManager layout, boolean isDoubleBuffered): Creates a new JPanel
with the specified layout manager and buffering strategy.
import javax.swing.*;
class JPanelExample {
JPanelExample(){
JFrame frame = new JFrame("Panel Example"); //create a frame
JPanel panel = new JPanel(); //Create JPanel Object
panel.setBounds(40,70,100,100); //set dimensions for Panel
JButton b = new JButton("ButtonInPanel"); //create JButton object
b.setBounds(60,50,80,40); //set dimensions for button
panel.add(b); //add button to the panel
frame.add(panel); //add panel to frame
frame.setSize(400,400);
frame.setLayout(null);
frame.setVisible(true);
}
}
public class Main {
public static void main(String[] args) {
new JPanelExample(); //create an object of FrameInherited class
}
}
JFrame:
The class JFrame is an extended version of java.awt.Frame that adds support for the
JFC/Swing component architecture.
Class Constructors:
import javax.swing.*;
JWindow
The class JWindow is a container that can be displayed but does not have the title
bar or window-management buttons.
Field
Class Constructors
Icons
Many Swing components, such as labels, buttons, and tabbed panes, can be
decorated with an icon — a fixed-sized picture. An icon is an object that adheres
to the Icon interface. Swing provides a particularly useful implementation of the
Icon interface: ImageIcon, which paints an icon from a GIF, JPEG, or PNG
image.
The program uses one image icon to contain and paint the yellow splats. One
statement creates the image icon and two more statements include the image
icon on each of the two labels:
ImageIcon icon = createImageIcon("images/middle.gif",
"a pretty but meaningless splat");
label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
label3 = new Jlabel(icon);
Example:
import javax.swing.ImageIcon;
import javax.swing.*;
public class ImageIconExample {
if (icon != null) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} else {
if (imgURL != null) {
} else {
System.err.println("Couldn't find file: " + path);
return null;
Painting in Swing
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class
1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle
with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw
line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current
font to the specified font.
Example
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas
{
public void paint(Graphics g)
{
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);
}
public static void main(String[] args)
{
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
}
Output:
Methods Description
void setText(String text) It defines the single line of text this component
will display.
Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JTextField
The object of a JTextField class is a text component that allows the editing of a
single line text.
It inherits JTextComponent class.
Example
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 Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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.
Methods Description
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);
}
}
Output:
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.
Methods
Modifier Method Description
and Type
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.
Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample()
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
JRadioButton
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.
It should be added in ButtonGroup to select one radio button only.
Example
import javax.swing.*;
public class RadioButtonExample
{
RadioButtonExample()
{
JFrame f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new RadioButtonExample();
}
}
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.
Example
import javax.swing.*;
public class TabbedPaneExample
{
TabbedPaneExample()
{
JFrame f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
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();
}
}
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.
Useful Methods
Modifier Method Description
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
Componen getCorner(String) be one of the following constants defined
t 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.
Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample
{
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
Output:
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.
Example
import javax.swing.*;
public class ListExample
{
ListExample()
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
JComboBox
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.
Example
import javax.swing.*;
public class ComboBoxExample
{
ComboBoxExample()
{
JFrame f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{
new ComboBoxExample();
}
}
Output:
Swing Menus
JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may
have several menus.
The object of JMenu class is a pull down menu component which is displayed from
the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in
a menu must belong to the JMenuItem or any of its subclass.
Output:
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.
Unlike JFrame, it doesn't have maximize and minimize buttons.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:
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.
Commonly used Constructors:
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:
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.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
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();
}
}
Output: