OOPJ UNIT - 5 Ece
OOPJ UNIT - 5 Ece
UNIT – 5
UNIT – V :
Exploring Swing- Japplet, Jframe and Jcomponent, Icons and Labels, Text Fields,
Buttons – The Jbutton Class, Check Boxes, Radio Buttons, Combo Boxes, Tabbed
• Secured
• A plugin is a software add-on that is installed on a program, enhancing its capabilities. For
example, if you wanted to watch a video on a website, you may need a plugin to do so. If
the plugin is not installed, your browser will not understand how to play the video.
Hierarchy of Applet
1.Applet is initialized.
2.Applet is started.
3.Applet is painted.
4.Applet is stopped.
5.Applet is destroyed.
Life cycle of an applet :
• It is important to understand the order in which the various methods shown in the
above image are called. When an applet begins, the following methods are called, in
this sequence:
1.init( )
2.start( )
3.paint( )
• When an applet is terminated, the following sequence of method calls takes place:
1.stop( )
2.destroy( )
Let’s look more closely at these methods:-
1.init( ) : The init( ) method is the first method to be called. This is where you should initialize
variables. This method is called only once during the run time of your applet.
2.start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it
has been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded
whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So,
if a user leaves a web page and comes back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based
applet’s output must be redrawn. This situation can occur for several
reasons. For example, the window in which the applet is running may be
applet begins execution. Whatever the cause, whenever the applet must
graphics context, which describes the graphics environment in which the applet is running.
Note: This is the only method among all the method mention above, which is parametrised.
It’s prototype is
containing the applet—when it goes to another page, for example. When stop( ) is called,
the applet is probably running. You should use stop( ) to suspend threads that don’t need to
run when the applet is not visible. You can restart them when start( ) is called if the user
5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
Lifecycle methods for Applet:
and
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
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.
Who is responsible to manage the life cycle of an applet?
//Simple.java
import java.applet.Applet;
import java.awt.Graphics;
public class Simple extends Applet
{ Note: class must be public because its object is
public void paint(Graphics g) created by Java Plugin software that resides on
{ the browser.
g.drawString(" A simple Applet ", 20, 20);
}
}
myapplet.html
<html>
<body>
<applet code="
Simple.class" width=“20" height=“20">
</applet>
</body>
</html>
Output:
Restrictions imposed on Java
applets
Due to security reasons , the following restrictions are
imposed on Java applets:
1.An applet cannot load libraries or define native
methods.
2.An applet cannot ordinarily read or write files on the
execution host.
3.An applet cannot read certain system properties.
4.An applet cannot make network connections except to
the host that it came from.
5.An applet cannot start any program on the host that’s
Difference between Applet and Application
• Java Application:
Java Application is just like a Java program that runs on an underlying
operating system with the support of a virtual machine. It is also known as
an application program. The graphical user interface is not necessary to execute the
java applications, it can be run with or without it.
• Java Applet:
An applet is a Java program that can be embedded into a web page. It runs inside
the web browser and works at client side. An applet is embedded in an HTML page
using the APPLET or OBJECT tag and hosted on a web server. Applets are used to
make the web site more dynamic and entertaining.
Java Application Java Applet
Applets are small Java programs that are designed to be included
Applications are just like a Java programs that can be execute with the HTML web document. They require a Java-enabled web
independently without using the web browser. browser for execution.
Application program requires a main function for its execution. Applet does not require a main function for its execution.
Java application programs have the full access to the local file system
and network. Applets don’t have local disk and network access.
Applets can only access the browser specific services. They don’t
Applications can access all kinds of resources available on the system. have access to the local system.
Applications can execute the programs from the local system. Applets cannot execute programs from the local machine.
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.
• 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.
Remote Applet
• 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).
Difference Between Local Applet and Remote Applet
Local Applet Remote Applet
There is no need to define the Applet's URL in Local We need to define the Applet's URL in Remote
Applet. Applet.
Local Applet is available on our computer. Remote Applet is not available on our computer.
In order to use it or access it, we don't need Internet In order to use it or access it on our computer, we
Connection. need an Internet Connection.
It is written on our own and then embedded into the It was written by another developer.
web pages.
• The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
</hr>
Passing Parameters to Applets
• To pass the parameters to the Applet we need to use the param attribute
of <applet> tag.
of Applet class.
Signature of the getParamter()
method
• Method takes a String argument name, which represents the name of the
parameter which was specified with the param attribute in the <applet> tag.
• Method returns the value of the name parameter(if it was defined) else null is
returned.
Simple example of Passing Parameters to Applets
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet8" width="400" height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination" value="California">
</applet>
*/
• The javax.swing package provides classes for java swing API such as
JButton,
The JTextField,
Java Foundation JTextArea,
Classes (JFC) areJRadioButton, JCheckbox,
a set of GUI components JMenu,
which
simplify the development
JColorChooser etc. of desktop applications.
Difference between AWT and Swing
Method Description
import javax.swing.*;
public class Simple { Output:
Simple(){
JFrame f=new JFrame();//
creating instance of JFrame
import javax.swing.*;
public class Simple2 extends Jframe Output:
{
//inheriting JFrame
JFrame f;
Simple2()
{
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
• 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.
• Second, the look and feel of each component was fixed and could not be changed.
provided by Swing fall into two general categories: GUI-state models and application-
data models. GUI state models are interfaces that define the visual status of a GUI
data model is an interface that represents some quantifiable data that the UI presents
The view is a UI component that is responsible for presenting data to the user. Thus it
is responsible for all UI dependent issues like layout, drawing, etc. JTable is a good
interaction (mouse motion, mouse click, key press, etc.). Controllers might need input for
their execution and they produce output. They read their input from models and update
ActionListener or Action.
Java JComponent
• 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.
Constructor
Constructor Description
JComponent() Default JComponent constructor.
Useful Methods
Modifier and Type Method Description
void setActionMap(ActionMap am) It sets the ActionMap to am.
void setBackground(Color bg) It sets the background color of this component.
String getToolTipText(MouseEvent event) It returns the string to be used as the tooltip for event.
• 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
• Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Constructor
Constructor Description
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen
device.
Useful Methods
Modifier and Type Method Description
protected void addImpl(Component comp, Object Adds the specified child Component.
constraints, int index)
protected createRootPane() Called by the constructor methods to
JRootPane create the default rootPane.
protected void frameInit() Called by the constructors to init the
JFrame properly.
void setContentPane(Containe contentPane) It sets the contentPane property
static void setDefaultLookAndFeelDecorated(boolea Provides a hint as to whether or not
n defaultLookAndFeelDecorated) newly created JFrames should have
their Window decorations (such as
borders, widgets to close the window,
title...) provided by the current look and
feel.
void setIconImage(Image image) It sets the image to be displayed as the
icon for this window.
void setJMenuBar(JMenuBar menubar) It sets the menubar for this frame.
void setLayeredPane(JLayeredPane It sets the layeredPane property.
layeredPane)
JRootPane getRootPane() It returns the rootPane object for this
frame.
Icons in Swing
• The setIconImage() method of Frame class is used to
change the icon of Frame or Window. It changes the
icon which is displayed at the left side of Frame or
Window.
• The Toolkit class is used to get instance of Image class
in AWT and Swing.
• Toolkit class is the abstract super class of every
implementation in the Abstract Window Toolkit(AWT).
Subclasses of Toolkit are used to bind various
components. It inherits Object class.
Example to change TitleBar icon in Java AWT
import javax.swing.*;
class IconExample
{
IconExample()
{
Output:
JFrame f=new JFrame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[])
{
new IconExample();
}
Java 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.
import javax.swing.*;
class LabelExample
{
public static void main(String args[]) Output:
{
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);
}
}
Java JTextField
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{ Output:
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);
}
}
Java 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.
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) { Output:
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example"); Output:
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();
}
}
Java JRadioButton
import javax.swing.*;
public class RadioButtonExample
{
RadioButtonExample()
{ Output:
JFrame f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
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();
}
Java 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.
import javax.swing.*;
public class ComboBoxExample {
ComboBoxExample(){
Output:
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();
}
}
Java JTabbedPane
Accessible, SwingConstants
Java JTabbedPane Example
import javax.swing.*;
public class TabbedPaneExample {
TabbedPaneExample(){
JFrame f=new JFrame();
JTextArea ta=new JTextArea(200,200); Output:
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();
}}
Java JScrollPane
Constructor Purpose
JScrollPane(int, int)
JScrollPane(Component, int,
int)
Useful Methods
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Output:
frame.getContentPane().add(s);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() )
{
public void run()
{
createAndShowGUI();
}
});
}
}
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[] 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.
Java JTree Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
TreeExample()
{
JFrame 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("bl
ack");
DefaultMutableTreeNode green=new DefaultMutableTreeNode(
"green");
color.add(red); color.add(blue); color.add(black); color.add(gree
n);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
Output:
Java JTable
Constructor Description
import javax.swing.*;
public class TableExample
{
TableExample() Output:
{
JFrame 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();
}
}