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

Oops_java Unit 5 Notes

The document provides an overview of Java Applets, highlighting their advantages, restrictions, lifecycle, and differences from Java applications. It explains the lifecycle methods of applets, the HTML APPLET tag, and the types of applets (local and remote), along with their differences. Additionally, it covers how to create and run applets, pass parameters, and introduces limitations of AWT and MVC architecture in GUI programming.

Uploaded by

vpvnspranay
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 views37 pages

Oops_java Unit 5 Notes

The document provides an overview of Java Applets, highlighting their advantages, restrictions, lifecycle, and differences from Java applications. It explains the lifecycle methods of applets, the HTML APPLET tag, and the types of applets (local and remote), along with their differences. Additionally, it covers how to create and run applets, pass parameters, and introduces limitations of AWT and MVC architecture in GUI programming.

Uploaded by

vpvnspranay
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/ 37

UNIT-5 APPLETS

Introduction to Java Applet

Introduction to 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 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

Figure: 13.1: Hierarchy of Apple


JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 238

Difference Between a Java Application and a Java Applet

Parameters Java Application Java Applet


Meaning and Basics A Java Application is a type of program that can A Java Applet is a small program that
get independently executed on a computer. makes use of another application program
so that we can execute it.

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.

Communication It is possible to establish communication with It cannot really establish communication


among other Servers the other servers. with the other servers.

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

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

The HTML APPLET Tag


As mentioned earlier, Sun currently recommends that the APPLET tag be used to start an
applet from both an HTML document and from an applet viewer.
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 242

...
[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 :

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.

VSPACE and HSPACE :

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.

PARAM NAME and VALUE :


The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets
access their attributes with the getParameter( ) method.Other valid APPLET attributes include
ARCHIVE, which lets you specify one or more archive files, and OBJECT, which specifies a
saved version 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.

Local Applet 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.

It is written on our own and then It was written by another developer.


embedded into the web pages.

We don't need to download it. It is available on a remote computer, so we need


to download it to our system.

Creating and Running an Applet


Running an Applet
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
1.Running an 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.
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>

2: Running 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 Filename.java. Now
Html file is not required but it is for testing purpose only

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

To execute the applet by appletviewer tool, write in command prompt:

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

Syntax: public String getParameter(String parameterName);

Example on Passing Parameters to Applets

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>
*/

public void paint(Graphics g)


{
String str=getParameter("Countryname");
g.drawString(str,50, 50);
}
}
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 248

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.

The Basic GUI Application

There are two basic types of GUI program in Java:

•Applets.

avy weight co•Stand-Alone Applications

An applet is a program that runs in a rectangular area on a Web page.

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.

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. This variability threatened java’s
philosophy: write once, run anywhere.
• Second, the look and feel of each component was fixed and could not be changed.
• Third,the use of heavyweight components caused some frustrating restrictions.

Summary on limitations of AWT

AWT supports limited number of GUI components

AWT component are He mponents

AWT components are developed by using platform specific code

AWT components behave differently in different Operating Systems.

11.3 MVC Architecture


In real time applications, in the case of server side programming one must follow the
architecture to develop a distributed application. To develop any distributed application, it is
always recommended to follow either 3-tier architecture or 2-tier architecture or n-tier
architecture.

3-tier architecture is also known as MVC architecture.

M stands for Model (database programming),

V stands for View (client side programming, HTML/AWT/APPLET/Swing/JSP) and

C stands for Controller (server side programming, Servlets).


JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 250

Model :

➢ It consists of all the data of the application


➢ It consists of classes which have the connection to the database.
➢ The model connects with the database as well and stores the data into a database
which is connected to it.

View :

➢ This is a presentation layer.


➢ It consists of HTML, JSP, etc. into it.
➢ It normally presents the UI of the application.
➢ It is used to display the data which is fetched from the controller which in turn
fetching data from model layer classes.
➢ This view layer shows the data on UI of the application.

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:

Figure 11.1 : MVC architecture

1. Client makes a request.


2. Server side program receives the request.
3. The server looks for or search for the appropriate resource in the resource pool.
4. If the resource is not available server side program displays a user friendly message (page
cannot be displayed). If the resource is available, that program will execute gives its result to
server, server interns gives response to that client who makes a request.
5. When server want to deals with database to retrieve the data, server side program sends a
request to the appropriate database.
6. Database server receives the server request and executes that request.
7. The database server sends the result back to server side program for further processing.
8. The server side program is always gives response to ‘n’ number of clients concurrently.
MVC in Swing
Swing actually uses a simplified variant of the MVC design called the model-delegate .
This design combines the view and the controller object into a single element, the UI delegate
, which draws the component to the screen and handles GUI events.
The communication between the model and the UI delegate then becomes a two-way street, as
shown in Figure below.
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 252

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:

protected void paintComponent(Graphics g)

The parameter g is the graphics context to which output is written.

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

Example on Creating a swing applet & painting in Swings

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

str=" welcome to SwingApplet programming";


repaint();
}

public void paintComponent(Graphics g)


{
super.paintComponent(g);
g.drawString(str, 2, 170);
}
}
Output:

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:

protected void paintComponent(Graphics g)

The parameter g is the graphics context to which output is written.

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

Hierarchy for swing components


Hierarchy for swing components

14.1 Exploring Swing Controls : JLable , Image Icon and JTextField


Exploring Swing Controls : JLable , Image Icon and JTextField

JLabels

A JLabel is a very simple component which contains a string.

The constructors are

➢ public JLabel() // creates label with no text


➢ public JLabel(String text) //create label with text

The methods available are

➢ public String getText() // return label text


➢ public void setText(String s) // sets the label text
Image Icon

The class ImageIcon is an implementation of the Icon interface that paints Icons from
Images.

The constructors are:

➢ ImageIcon() // Creates an uninitialized image icon.


➢ ImageIcon(Image image)// Creates an ImageIcon from an image object.
➢ ImageIcon(Image image, String description)// Creates an ImageIcon from the image.
➢ ImageIcon(String filename, String description)// Creates an ImageIcon from the
specified file.
➢ ImageIcon(URL location)// Creates an ImageIcon from the specified URL.

The methods available are

➢ String getDescription() // Gets the description of the image


➢ Image getImage()//Returns this icon's Image.
➢ void paintIcon(Component c, Graphics g, int x, int y)// Paints the icon.
➢ void setDescription(String description)// Sets the description of the image.
➢ void setImage(Image image)// Sets the image displayed by this icon.
➢ String toString()//Returns a string representation of this image

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.

The constructors are :

➢ public JTextField () // creates text field with no text


➢ public int columns JTextField () // create text field with appropriate # of columns
➢ public JTextField (String s) // create text field with s displayed
➢ public JTextField (String s, int columns) // create text field with s displayed &
approp. width

Methods include:

➢ public void setEditable(boolean s) // if false the TextField is not user editable


➢ public String getText() // return label text
➢ public void setText(String s) // sets the label text
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 258

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.

Commonly used Methods of Abstract Button 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.

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

14.2.2 JToggle Button


A toggle button looks just like a push button, but it acts differently because it has two
states: pushed and released. That is, when you press toggle button, it stays pressed rather than
popping back up as a regular push button does. When you press the toggle button a second
time, it releases (pops up). Therefore, each time a toggle button is pushed it toggles between
its two states

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:

14.2.3 JCheck Box

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
Creates an initially unselected check box
JJCheckBox()
button with no text, no icon.
Creates an initially unselected check box
JChechBox(String s)
with text.
Creates a check box with text and specifies
JCheckBox(String text, boolean selected)
whether or not it is initially selected.
Creates a check box where properties are
JCheckBox(Action a)
taken from the Action supplied.

Commonly used Methods:

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

Example program to demonstrate JCheckBox

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:

14.2.4 JRadio Button


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
Creates an unselected radio button with no
JRadioButton()
text.
Creates an unselected radio button with
JRadioButton(String s)
specified text.
Creates a radio button with the specified text
JRadioButton(String s, boolean selected)
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.
It is used to set the specified Icon on the
void setIcon(Icon b)
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.
It is used to add the action listener to this
void addActionListener(ActionListener a)
object.
example program on JRadioButton

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:

14.2.8 JCombo Box


Swing provides a combo box (a combination of a text field and a drop-down list) through the
JComboBox class. A combo box normally displays one entry, but it will also display a drop-
down list that allows a user to select a different entry.

The JComboBox constructor used by the example is shown here:


JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box.
In addition to passing an array of items to be displayed in the drop-down list, items canbe
dynamically added to the list of choices via the addItem( ) method, shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box. One way to obtain the item selected in
the list is to call getSelectedItem( ) on the combobox. It is shown here:
Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in the list.
Example program on JComboBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code="JComboBoxDemo" width=300 height=100> </applet> */
public class JComboBoxDemo extends JApplet {
JLabel jlab; JComboBox jcb;
String chocolates[] = { "fivestar", "DairyMilk", "kitkat"};
public void init() {
setLayout(new FlowLayout());// Change to flow layout.
jcb = new JComboBox(chocolates); // Instantiate a combo box add(jcb);
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".JPG"));
}
});
jlab = new JLabel(new ImageIcon("fivestar.JPG"));// Create a label and add it to
the content pane.
add(jlab);
}
}
Output:
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 266

14.2.5 JTabbed Pane


JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with
tabs. Selecting a tab causes the component associated with that tab to come to the forefront

void addTab(String name, Component comp)

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

The general procedure to use a tabbed pane is outlined here:

1. Create an instance of JTabbedPane.

2. Add each tab by calling addTab( ).

3. Add the tabbed pane to the content pane

Example to illustrates a Tabbed Pane.

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

JScrollPane is a lightweight container that automatically handles the scrolling of

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)

The component to be scrolled is specified by comp. Scroll bars are automatically


displayed when the content of the pane exceeds the dimensions of the viewport.

Here are the steps to follow to use a scroll pane:


1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.

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


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

1. public class JTree extends JComponent implements Scrollable, Accessible

Commonly used Constructors:


Constructor Description

JTree() Creates a JTree with a sample model.

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 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();
}}
JAVA PROGRAMMING CHAPTER 13: Swing Application &Applets PAGE NO: 272

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

JTable class declaration


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

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","ABC","67"},

{"102","DEF","78"},

{"101","GHI","70"}};

String column[]={"ID","NAME","Markspercentage"};

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:

You might also like