0% found this document useful (0 votes)
3 views20 pages

ssc gd

Java Swing is a part of Java Foundation Classes (JFC) for creating window-based applications, offering platform-independent and lightweight components. It includes various classes like JButton, JTextField, and JTabbedPane, and differs from AWT by supporting pluggable look and feel, providing more components, and following the MVC architecture. The document also provides examples and descriptions of commonly used methods for various Swing components.

Uploaded by

peddikittu790
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

ssc gd

Java Swing is a part of Java Foundation Classes (JFC) for creating window-based applications, offering platform-independent and lightweight components. It includes various classes like JButton, JTextField, and JTabbedPane, and differs from AWT by supporting pluggable look and feel, providing more components, and following the MVC architecture. The document also provides examples and descriptions of commonly used methods for various Swing components.

Uploaded by

peddikittu790
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit 5 - Swing, Applets

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 as JButton, JTextField, JTextArea, JRadioButton,JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java AWT and swing that are given below.
S.No. Java AWT Java Swing
Java swing components are platform-
1) AWT components are platform-dependent.
independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
Swing provides more powerful components
4) AWT provides less components than Swing. such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
AWT doesn't follows MVC(Model View Controller) where
model represents data, view represents presentation
5) Swing follows MVC.
and controller acts as an interface between model and
view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.

Hierarchy of Java Swing classes

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 1


Commonly used Methods of Component class
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:

 By creating the object of Frame class (association)


 By extending Frame class (inheritance)

Example1:
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);
}
}
Example2:
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample2 {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to SCITS, KNR.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 2


Example3:

import javax.swing.*;
public class Simple2 extends JFrame{
JFrame f;
Simple2(){
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);
add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
}

public static void main(String[] args) {


new Simple2();
}
}

Example4:

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);
}
}

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 3


Swing Controls
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.
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and horizontal
horizontalAlignment) alignment.
Commonly used Methods:
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It inherits
JTextComponent class.

JTextField class declaration

public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:


Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified number of columns.

Commonly used Methods:


Methods Description
It is used to add the specified action listener to receive action events from this
void addActionListener(ActionListener l)
textfield.
It returns the currently set Action for this ActionEvent source, or null if no
Action getAction()
Action is set.
void setFont(Font f) It is used to set the current font.
void It is used to remove the specified action listener so that it no longer receives
removeActionListener(ActionListener l) action events from this textfield.

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 4


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.

JButton class declaration


public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Commonly used Methods of AbstractButton class:
Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes
Modifier and Class Description
Type
protected class JToggleButton.AccessibleJToggleButton This class implements accessibility support for the
JToggleButton class.
static class JToggleButton.ToggleButtonModel The ToggleButton model

Constructors
Constructor Description
JToggleButton() It creates an initially unselected toggle button without setting the text or
image.
JToggleButton(Action a) It creates a toggle button where properties are taken from the Action
supplied.
JToggleButton(Icon icon) It creates an initially unselected toggle button with the specified image
but no text.
JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specified image and selection state,
but no text.
JToggleButton(String text) It creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean selected) It creates a toggle button with the specified text and selection state.
JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and image, and that
is initially unselected.
JToggleButton(String text, Icon icon, boolean It creates a toggle button with the specified text, image, and selection
R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 5
selected) state.
Methods
Modifier and Method Description
Type
AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this JToggleButton.
String getUIClassID() It returns a string that specifies the name of the l&f class that renders this
component.
protected String paramString() It returns a string representation of this JToggleButton.
void updateUI() It resets the UI property to a value from the current look and feel.

JToggleButton Example

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener {


public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 6


Java 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.

Let's see the declaration for javax.swing.JTabbedPane class.

public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants

Commonly used Constructors:

Constructor Description
JTabbedPane() Creates an empty TabbedPane with a default tab placement of
JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement and tab
tabLayoutPolicy) layout policy.

Java JTabbedPane Example


import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
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();
}
}

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 7


Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits
JTextComponent class

Let's see the declaration for javax.swing.JTextArea class.

public class JTextArea extends JTextComponent

Commonly used Constructors:


Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns that displays no
text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns that displays
column) specified text.

Commonly used Methods:


Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.

Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It allows the editing of a single
line of text. It inherits JTextField class.

Let's see the declaration for javax.swing.JPasswordField class.

public class JPasswordField extends JTextField

Commonly used Constructors:

Constructor Description
Constructs a new JPasswordField, with a default document, null starting text string,
JPasswordField()
and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.
JPasswordField(String text, int
Construct a new JPasswordField initialized with the specified text and columns.
columns)

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 8


Java 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.

JCheckBox class declaration


public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:

Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is initially
selected) selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied.

Commonly used Methods:

Methods Description
AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.

Java 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.

JRadioButton class declaration


public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:

Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.

Commonly used Methods:

Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 9


Java 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.

JTabbedPane class declaration


public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants

Java JScrollBar

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a scrollbar. It
inherits JComponent class.

JScrollBar class declaration


public class JScrollBar extends JComponent implements Adjustable, Accessible
Commonly used Constructors:
Constructor Description
JScrollBar() Creates a vertical scrollbar with the initial values.
Creates a scrollbar with the specified orientation and the initial
JScrollBar(int orientation)
values.
JScrollBar(int orientation, int value, int extent, int Creates a scrollbar with the specified orientation, value, extent,
min, int max) minimum, and maximum.

Java 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.
JList class declaration
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.

Commonly used Methods:


Methods Description
Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified each time a
listener) change to the selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an array of
objects.

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 10


Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
ofa menu. It inherits JComponent class.

JComboBox class declaration

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener,


Accessible

Commonly used Constructors:

Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.

Commonly used Methods:

Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.

Java 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 theJMenuItem
class. The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to
theJMenuItem or any of its subclass.

JMenuBar class declaration


public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration


public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration


public class JMenuItem extends AbstractButton implements Accessible, MenuElement

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 11


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. Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration

public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer

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 class declaration


public class JTree extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JTree() Creates a JTree with a sample model.
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 {
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();
}}

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 12


Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

Commonly used Constructors:


Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example


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();
}
}

Java 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() It creates a scroll pane. The Component parameter, when present, sets the scroll
JScrollPane(Component) pane's client. The two int parameters, when present, set the vertical and
JScrollPane(int, int) horizontal scroll bar policies (respectively).
JScrollPane(Component, int, int)

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 13


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
Component getCorner(String) corner and 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.
void setViewportView(Component) Set the scroll pane's client.

JScrollPane 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() {
final JFrame frame = new JFrame("Scroll Pane Example");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 14


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

There are many advantages of applet. They are as follows:

1. It works at client side so less response time.


2. Secured
3. It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc.

Drawback of Applet
1. Plugin is required at client browser to execute applet.

Hierarchy of Applet

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.

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 15


Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an
applet.

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).

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 16


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.

//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.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:

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.

//First.java
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

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 17


Event Handling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple
example of event handling in applet that prints a message by click on the button.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>

Security Issues in Applet


What Applets Can and Cannot Do

Java applets are loaded on a client when the user visits a page containing an applet. The security model behind
Java applets has been designed with the goal of protecting the user from malicious applets.

Applets are either sandbox applets or privileged applets. Sandbox applets are run in a security sandbox that
allows only a set of safe operations. Privileged applets can run outside the security sandbox and have extensive
capabilities to access the client.

Applets that are not signed are restricted to the security sandbox, and run only if the user accepts the applet.
Applets that are signed by a certificate from a recognized certificate authority can either run only in the sandbox,
or can request permission to run outside the sandbox. In either case, the user must accept the applet's security
certificate, otherwise the applet is blocked from running.

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 18


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)

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>

JApplet class in Applet


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.*;
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);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 19
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
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.

Painting in Applet

We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.


/*<applet code="MouseDrag.class" width="300" height="300"> */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red); }
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5); }
public void mouseMoved(MouseEvent me){}
}
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis.
ThegetGraphics() method of Component class returns the object of Graphics.

R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 20

You might also like