You are on page 1of 33

UNIT-IV

I/O STREAMS AND APPLET

SYLLABUS:

Character Streams, Stream I/O, Serialization, Files, Applet Architecture, Programming


using Applet, Event Handling Delegation event Model, Event classes, Event Listener Interface.

I/O STREAMS:

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous flow of
data. Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,

1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes

Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.
Some important Byte stream classes.

Stream class Description


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard
datatype
DataOutputStream An output stream that contain method for
writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println()
method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes.


Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println()
method.
Reader Abstract class that define character stream
input
Writer Abstract class that define character stream
output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException

Below is a simple example explaining character input:

class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.

String readLine() throws IOException


Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Program to write to a File using FileWriter class
import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
SERIALIZATION AND DESERIALIZATION
Serialization is a process of converting an object into a sequence of bytes which can be
persisted to a disk or database or can be sent through streams. The reverse process of creating
object from sequence of bytes is called deserialization.

A class must implement Serializable interface present in java.io package in order to


serialize its object successfully. Serializable is a marker interface that adds serializable
behaviour to the class implementing it.

Java provides Serializable API encapsulated under java.io package for serializing and
deserializing objects which include,

 java.io.serializable
 java.io.Externalizable
 ObjectInputStream
 and ObjectOutputStream etc

Marker interface
Marker Interface is a special interface in Java without any field and method. Marker interface
is used to inform compiler that the class implementing it has some special behaviour or meaning.
Some example of Marker interface are,

 java.io.serializable
 java.lang.Cloneable
 java.rmi.Remote
 java.util.RandomAccess

All these interfaces does not have any method and field. They only add special behavior to
the classes implementing them. However marker interfaces have been deprecated since Java 5,
they were replaced by Annotations. Annotations are used in place of Marker Interface that play
the exact same role as marker interfaces did before.

Signature of writeObject() and readObject()


writeObject() method of ObjectOutputStream class serializes an object and send it to the
output stream.

public final void writeObject(object x) throws IOException

readObject() method of ObjectInputStream class references object out of stream and


deserialize it.

public final Object readObject() throws IOException,ClassNotFoundException

while serializing if you do not want any field to be part of object state then declare it
either static or transient based on your need and it will not be included during java serialization
process.

Serializing an Object

import java.io.*;
class studentinfo implements Serializable

String name;

int rid;

static String contact;

studentinfo(string n, int r, string c)

this.name = n;

this.rid = r;

this.contact = c;

class Test

public static void main(String[] args)

try

{
Studentinfo si = new studentinfo("Abhi", 104, "110044");

FileOutputStream fos = new FileOutputStream("student.ser");

Objectoutputstream oos = new ObjectOutputStream(fos);

oos.writeObject(si);

oos.close();

fos.close();

catch (Exception e)

e.printStackTrace();

}
}
Object of Studentinfo class is serialized using writeObject() method and written
to student.ser file.

Deserialization of Object

import java.io * ;

class DeserializationTest

public static void main(String[] args)


{

studentinfo si=null ;

try

FileInputStream fis = new FileInputStream("student.ser");

ObjectOutputStream ois = new ObjectOutputStream(fis);

si = (studentinfo)ois.readObject();

catch (Exception e)

e.printStackTrace(); }

System.out.println(si.name);

System.out. println(si.rid);

System.out.println(si.contact);

Output :
Abhi
104
null
Contact field is null because,it was marked as static and as we have discussed earlier static fields
does not get serialized.
NOTE: Static members are never serialized because they are connected to class not object of
class.
transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient. transient keyword will prevent that data member from being
serialized.

class studentinfo implements Serializable

String name;

transient int rid;

static String contact;

 Making a data member transient will prevent its serialization.


 In this example rid will not be serialized because it is transient, and contact will also remain
unserialized because it is static.

Applet in Java

 Applets are small Java applications that can be accessed on an Internet server, transported
over Internet, and can be automatically installed and run as apart of a web document.
 After a user receives an applet, the applet can produce a graphical user interface. It has
limited access to resources so that it can run complex computations without introducing the
risk of viruses or breaching data integrity.
 Any applet in Java is a class that extends the java.applet.Applet class.
 An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.
 JVM creates an instance of the applet class and invokes init() method to initialize an Applet.
A Simple Applet
import java.awt.*;

import java.applet.*;

public class Simple extends Applet

public void paint(Graphics g)

g.drawString("A simple Applet", 20, 20);

Every Applet application must import two packages - java.awt and java.applet.

java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a window-
based, graphical user interface. java.applet.* imports the applet package, which contains the class
Applet. Every applet that you create must be a subclass of Applet class.

The class in the program must be declared as public, because it will be accessed by code
that is outside the program.Every Applet application must declare a paint() method. This method
is defined by AWT class and must be overridden by the applet. The paint() method is called each
time when an applet needs to redisplay its output. Another important thing to notice about applet
application is that, execution of an applet does not begin at main() method. In fact an applet
application does not have any main() method.

Advantages of Applets

1. It takes very less response time as it works on the client side.


2. It can be run on any browser which has JVM running in it.

Applet class

Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load
and play audio clips.

An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.

 init() : init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.
 start() : start() method is called after init(). This method is called to restart an applet after it
has been stopped.
 stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
 destroy() : destroy() method is called when your applet needs to be removed completely
from memory.

Note: The stop() method is always called before destroy() method.

Example of an Applet Skeleton


import java.awt.*;

import java.applet.*;

public class AppletTest extends Applet

{
public void init()

//initialization

public void start ()

//start or resume execution

public void stop()

//suspend execution

public void destroy()

//perform shutdown activity

public void paint (Graphics g)

//display the content of window

Example of an Applet
import java.applet.*;

import java.awt.*;

public class MyApplet extends Applet


{

int height, width;

public void init()

height = getSize().height;

width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

g.drawRoundRect(10, 30, 120, 120, 2, 3);

How to run an Applet Program


An Applet program is compiled in the same way as you have been compiling your console
programs. However there are two ways to run an applet.

 Executing the Applet within Java-compatible web browser.


 Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes
your applet in a window

For executing an Applet in an web browser, create short HTML file in the same directory.
Inside bodytag of the file, include the following code. (applet tag loads the Applet class)
< applet code = "MyApplet" width=400 height=400 >

< /applet >

Run the HTML file

Running Applet using Applet Viewer


To execute an Applet with an applet viewer, write short HTML file as discussed above. If
you name it as run.htm, then the following command will run your applet program.
f:/>appletviewer run.htm

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any serious
applet −

 init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.

 start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.

 stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.

 destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.

 paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.
APPLET ARCHITECTURE:

When you write a Java application for time series data, you use the JDBC Driver to
connect to the database, as shown in the following figure.

Figure 1. Runtime architecture for Java programs that connect to a database

The Java application makes calls to the JDBC driver, which sends queries and other SQL
statements to the database. The database sends query results to the JDBC driver, which sends
them on to the Java application.
You can also use the time series Java classes in Java applets and servlets, as shown in the
following figures.

Figure 2. Runtime architecture for a Java applet


The database server is connected to the JDBC driver, which is connected to the applet. The
applet is also connected to a browser, which is connected to a web server that communicates
with the database.

Figure 3. Runtime architecture for a Java servlet

A request from an application goes through a web server, an HTTP servlet subclass, and
the JDBC driver to the database. The database sends responses back along the same path.

PROGRAMMING USING APPLET:

Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Example of Graphics in applet:


import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}

myapplet.html

<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Displaying Image in Applet

Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:

1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}

public void paint(Graphics g) {


g.drawImage(picture, 30,30, this);
}
}
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

myapplet.html

1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
moved.

Example of animation in applet:


1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. g.drawImage(picture, i,30, this);
14.
15. try{Thread.sleep(100);}catch(Exception e){}
16. }
17. }
18. }
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

myapplet.html

1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change in state of any object. For Example
: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified when an
event occurs.
How Events are handled ?
A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by
a number of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interface

Event Classes Description Listener Interface


ActionEvent generated when button is ActionListener
pressed, menu-item is
selected, list-item is double
clicked
MouseEvent generated when mouse is MouseListener
dragged,
moved,clicked,pressed or
released and also when it
enters or exit a component
KeyEvent generated when input is KeyListener
received from keyboard
ItemEvent generated when check-box or ItemListener
list item is clicked
TextEvent generated when value of TextListener
textarea or textfield is changed
MouseWheelEvent generated when mouse wheel MouseWheelListener
is moved
WindowEvent generated when window is WindowListener
activated, deactivated,
deiconified, iconified, opened
or closed
ComponentEvent generated when component is ComponentEventListener
hidden, moved, resized or set
visible
ContainerEvent generated when component is ContainerListener
added or removed from
container
AdjustmentEvent generated when scroll bar is AdjustmentListener
manipulated
FocusEvent generated when component FocusListener
gains or loses keyboard focus
Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.

Example of Event Handling


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class Test extends Applet implements KeyListener


{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code :
< applet code="Test" width=300, height=100 >

Event Handling Model


The working of an event-driven program is governed by its underlying event-handling model.
Till now two models have been introduced in Java for receiving and processing events. The
event handling mechanisms of these models differ a lot from each other.
Java 1.0 Event Model
The Java 1.0 Event model for event processing was based on the concept of containment.
In this approach, when a user-initiated event is generated it is first sent to the component in
which the event has occurred. But in case the event is not handled at this component, it is
automatically propagated to the container of that component. This process is continued until the
event .is processed or it reaches the root of the containment hierarchy.
For example, as shown in the Figure, Button is contained in the Panel which itself is
contained within the Frame. When the mouse is clicked on Button, an event is generated which
is first sent to the Button. If it is not handled by it then this event is forwarded to the Panel and if
it cannot handle the event, it is further sent to the Frame. Frame being the root of the given
hierarchy processes this event. So the event is forwarded up the containment hierarchy until it is
handled by a component.

The major drawback in this approach is that events could be handled by the component
that generated it or by the container of that component. Another problem is that events are
frequently sent to those components that cannot process them, thus wasting a lot of CPU cycles.
Delegation Event Model
The advanced versions of Java ruled out the limitations of Java 1.0 event model. This
model is referred to as the Delegation Event Model which defines a logical approach to handle
events. It is based on the concept of source and listener. A source generates an event and sends it
to one or more listeners. On receiving the event, listener processes the event and returns it. The
notable feature of this model is that the source has a registered list of listeners which will receive
the events as they occur. Only the listeners that have been registered actually receive the
notification when a specific event is generated.
For example, as shown in Figure, when the mouse is clicked on Button, an event is
generated. If the Button has a registered listener to handle the event, this event is sent
to Button, processed and the output is returned to the user. However, if it has no registered
listener the event will not be propagated upwards to Panel or Frame.
Now we discuss Event Source and Event Listener in detail.
• Event source: An event source is an object that generates a particular kind of event. An event
is generated when the internal state of the event source is changed. A source may generate more
than one type of event. Every source must register a list of listeners that are interested to receive
the notifications regarding the type of event. Event source provides methods to add or remove
listeners.
The general form of method to register (add) a listener is:
public void addTypeListener(TypeListener eventlistener)
Similarly, the general form of method to unregister (remove) a listener is:
public void removeTypeListener(TypeListener eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
• Event listener: An event listener is an object which receives notification when an event occurs.
As already mentioned, only registered listeners can receive notifications from sources about
specific types of events. The role of event listener is to receive these notifications and process
them

Java - Event Listeners Example in Java Applet


Introduction
The event listener is the feature of java that handles the several events for the several
objects, Such as:MouseEvent, KeyEvent, TextEvent, InputEvent etc. Classes for helping in
implementing event listeners are present in thejava.awt.event.*; package. So, to use the events
handling in your application import the java.awt.event.*; package. This example illustrates that
how to handle several events fired on the several objects.

In this example you will see that how to use the event listener and to perform appropriate
tasks. In this example the EventListeners.java is our applet class which implements the
ActionListener interface. Here four buttons and integer types variables have been used with
specific values to perform the Addition, Subtraction, Multiplication and Division operations. All
these operations are controlled by the events generated by these buttons. The Text Area
named txtAreaholds the result of the operation. There are two methods
like init() and actionPerformed() have been used in this program for performing the whole
operation.

To handle the events generated by these buttons you add action listeners
e.g. object_name.addActionListener(this);.
When the action event occurs, that object's actionPerformed method is invoked.
actionPerformed(ActionEvent e)

Here is the java code of the program:


import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class EventListeners extends Applet implements ActionListener{


TextArea txtArea;
String Add, Subtract,Multiply,Divide;
int i = 10, j = 20, sum =0,Sub=0,Mul = 0,Div = 0;

public void init(){


txtArea = new TextArea(10,20);
txtArea.setEditable(false);
add(txtArea,"center");
Button b = new Button("Add");
Button c = new Button("Subtract");
Button d = new Button("Multiply");
Button e = new Button("Divide");
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);

add(b);
add(c);
add(d);
add(e);
}

public void actionPerformed(ActionEvent e){


sum = i + j;
txtArea.setText("");
txtArea.append("i = "+ i + "\t" + "j = " + j + "\n");
Button source = (Button)e.getSource();
if(source.getLabel() == "Add"){
txtArea.append("Sum : " + sum + "\n");
}

if(i >j){
Sub = i - j;
}
else{
Sub = j - i;
}
if(source.getLabel() == "Subtract"){
txtArea.append("Sub : " + Sub + "\n");
}

Mul = i*j;
if(source.getLabel() == "Multiply"){
txtArea.append("Mul = " + Mul + "\n");
}

if(i > j){


Div = i / j;
}
else{
Div = j / i;
}

if(source.getLabel() == "Divide"){
txtArea.append("Divide = " + Div);
}
}
}
Here is the HTML code of the program :
<HTML>
<BODY>
<APPLET CODE ="EventListeners" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>

EVENTLISTENER INTERFACES
An event listener registers with an event source to receive notifications about the events
of a particular type.
Various event listener interfaces defined in the java.awt.event package are given below :
Interface Description
ActionListener Defines the actionPerformed() method to
receive and process action events.
MouseListener Defines five methods to receive mouse events,
such as when a mouse is clicked, pressed,
released, enters, or exits a component
MouseMotionListener Defines two methods to receive events, such
as when a mouse is dragged or
moved.
AdjustmentListner Defines the adjustmentValueChanged()
method to receive and process the
adjustment events.
TextListener Defines the textValueChanged() method to
receive and process an event when the text
value changes.
WindowListener Defines seven window methods to receive
events.

ItemListener Defines the itemStateChanged() method when


an item has been selected or deselected by the
user.

Example :
The following code shows the generation of an action event and its handling by the
ActionListener interface :
package corejava;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionListenerDemo extends JFrame implements ActionListener {
JButton b1, b2;
JLabel lbl;
int clicked;
final String str = " Number of times button clicked = ";
public ActionListenerDemo(String strName) {
super(strName);
getContentPane().setLayout(new FlowLayout());
JPanel p = new JPanel();
b1 = new JButton("Click Me");
b2 = new JButton("Quit");
p.setLayout(new FlowLayout());
p.add(b1);
p.add(b2);
lbl = new JLabel(str + clicked, JLabel.CENTER);
getContentPane().add(p);
getContentPane().add(lbl);
b1.addActionListener(this);
b2.addActionListener(this);
}

public void actionPerformed(ActionEvent ae) {


String s = ae.getActionCommand();
if ("Click Me".equals(s)) {
clicked++;
lbl.setText(str + clicked);
}
if ("Quit".equals(s)) {
System.exit(0);
}
}
public static void main(String args[]) {
ActionListenerDemo t = new ActionListenerDemo("Action Events");
t.setSize(300, 300);
t.setVisible(true);
}
}
Output :
It will display the number of time you clicked "Click Me" button :

You might also like