Advance Java Unit - 2

 UNIT 2: Multithreading, Applet and Event Handling 




Java Threads | How to create a thread in Java

There are two ways to create a thread:

  1. By extending Thread class

  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

  • Thread()

  • Thread(String name)

  • Thread(Runnable r)

  • Thread(Runnable r,String name)

Commonly used methods of Thread class:

  1. public void run(): is used to perform action for a thread.

  2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.

  3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

  4. public void join(): waits for a thread to die.

  5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

  6. public int getPriority(): returns the priority of the thread.

  7. public int setPriority(int priority): changes the priority of the thread.

  8. public String getName(): returns the name of the thread.

  9. public void setName(String name): changes the name of the thread.

  10. public Thread currentThread(): returns the reference of currently executing thread.

  11. public int getId(): returns the id of the thread.

  12. public Thread.State getState(): returns the state of the thread.

  13. public boolean isAlive(): tests if the thread is alive.

  14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.

  15. public void suspend(): is used to suspend the thread(depricated).

  16. public void resume(): is used to resume the suspended thread(depricated).

  17. public void stop(): is used to stop the thread(depricated).

  18. public boolean isDaemon(): tests if the thread is a daemon thread.

  19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

  20. public void interrupt(): interrupts the thread.

  21. public boolean isInterrupted(): tests if the thread has been interrupted.

  22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

  1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:



Java Threads | How to create a thread in Java

There are two ways to create a thread:

  1. By extending Thread class

  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

  • Thread()

  • Thread(String name)

  • Thread(Runnable r)

  • Thread(Runnable r,String name)

Commonly used methods of Thread class:

  1. public void run(): is used to perform action for a thread.

  2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.

  3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

  4. public void join(): waits for a thread to die.

  5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

  6. public int getPriority(): returns the priority of the thread.

  7. public int setPriority(int priority): changes the priority of the thread.

  8. public String getName(): returns the name of the thread.

  9. public void setName(String name): changes the name of the thread.

  10. public Thread currentThread(): returns the reference of currently executing thread.

  11. public int getId(): returns the id of the thread.

  12. public Thread.State getState(): returns the state of the thread.

  13. public boolean isAlive(): tests if the thread is alive.

  14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.

  15. public void suspend(): is used to suspend the thread(depricated).

  16. public void resume(): is used to resume the suspended thread(depricated).

  17. public void stop(): is used to stop the thread(depricated).

  18. public boolean isDaemon(): tests if the thread is a daemon thread.

  19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

  20. public void interrupt(): interrupts the thread.

  21. public boolean isInterrupted(): tests if the thread has been interrupted.

  22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

  1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:




Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:

  1. New

  2. Active

  3. Blocked / Waiting

  4. Timed Waiting

  5. Terminated

Explanation of Different Thread States

New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states within it: one is runnable, and the other is running.

  • Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
    A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.

  • Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state.


Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

  • When a thread has finished its job, then it exists or terminates normally.

  • Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.


Implementation of Thread States

In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java provides the constants ENUM to represent the state of a thread. These constants are:

  1. public static final Thread.State NEW  

It represents the first state of a thread that is the NEW state.

  1. public static final Thread.State RUNNABLE  

It represents the runnable state.It means a thread is waiting in the queue to run.

  1. public static final Thread.State BLOCKED  

It represents the blocked state. In this state, the thread is waiting to acquire a lock.

  1. public static final Thread.State WAITING  

It represents the waiting state. A thread will go to this state when it invokes the Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting state is waiting for another thread to complete its task.

  1. public static final Thread.State TIMED_WAITING  

It represents the timed waiting state. The main difference between waiting and timed waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has the time constraint. A thread invoking the following method reaches the timed waiting state.



Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority

Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).



3 constants defined in Thread class:

  1. public static int MIN_PRIORITY

  2. public static int NORM_PRIORITY

  3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

FileName: ThreadPriorityExample.java

  1. // Importing the required classes  

  2. import java.lang.*;  

  3.   

  4. public class ThreadPriorityExample extends Thread   

  5. {  

  6.   

  7. // Method 1  

  8. // Whenever the start() method is called by a thread  

  9. // the run() method is invoked  

  10. public void run()  

  11. {  

  12. // the print statement  

  13. System.out.println("Inside the run() method");  

  14. }  

  15.   

  16. // the main method  

  17. public static void main(String argvs[])  

  18. {  

  19. // Creating threads with the help of ThreadPriorityExample class  

  20. ThreadPriorityExample th1 = new ThreadPriorityExample();  

  21. ThreadPriorityExample th2 = new ThreadPriorityExample();  

  22. ThreadPriorityExample th3 = new ThreadPriorityExample();  

  23.   

  24. // We did not mention the priority of the thread.  

  25. // Therefore, the priorities of the thread is 5, the default value  

  26.   

  27. // 1st Thread  

  28. // Displaying the priority of the thread  

  29. // using the getPriority() method  

  30. System.out.println("Priority of the thread th1 is : " + th1.getPriority());  

  31.   

  32. // 2nd Thread   

  33. // Display the priority of the thread  

  34. System.out.println("Priority of the thread th2 is : " + th2.getPriority());  

  35.   

  36. // 3rd Thread   

  37. // // Display the priority of the thread  

  38. System.out.println("Priority of the thread th2 is : " + th2.getPriority());  

  39.   

  40. // Setting priorities of above threads by  

  41. // passing integer arguments  

  42. th1.setPriority(6);  

  43. th2.setPriority(3);  

  44. th3.setPriority(9);  

  45.   

  46. // 6  

  47. System.out.println("Priority of the thread th1 is : " + th1.getPriority());  

  48.   

  49. // 3  

  50. System.out.println("Priority of the thread th2 is : " + th2.getPriority());  

  51.   

  52. // 9  

  53. System.out.println("Priority of the thread th3 is : " + th3.getPriority());  

  54.   

  55. // Main thread  

  56.   

  57. // Displaying name of the currently executing thread   

  58. System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());  

  59.   

  60. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  

  61.   

  62. // Priority of the main thread is 10 now  

  63. Thread.currentThread().setPriority(10);  

  64.   

  65. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  

  66. }  

  67. }  

Synchronization in Java

Synchronization in Java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Why use Synchronization?

The synchronization is mainly used to

  1. To prevent thread interference.

  2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

  1. Process Synchronization

  2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

  1. Mutual Exclusive

    1. Synchronized method.

    2. Synchronized block.

    3. Static synchronization.

  2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:

  1. By Using Synchronized Method

  2. By Using Synchronized Block

  3. By Using Static Synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

TestSynchronization1.java

  1. class Table{  

  2. void printTable(int n){//method not synchronized  

  3.    for(int i=1;i<=5;i++){  

  4.      System.out.println(n*i);  

  5.      try{  

  6.       Thread.sleep(400);  

  7.      }catch(Exception e){System.out.println(e);}  

  8.    }  

  9.   

  10.  }  

  11. }  

  12.   

  13. class MyThread1 extends Thread{  

  14. Table t;  

  15. MyThread1(Table t){  

  16. this.t=t;  

  17. }  

  18. public void run(){  

  19. t.printTable(5);  

  20. }  

  21.   

  22. }  

  23. class MyThread2 extends Thread{  

  24. Table t;  

  25. MyThread2(Table t){  

  26. this.t=t;  

  27. }  

  28. public void run(){  

  29. t.printTable(100);  

  30. }  

  31. }  

  32.   

  33. class TestSynchronization1{  

  34. public static void main(String args[]){  

  35. Table obj = new Table();//only one object  

  36. MyThread1 t1=new MyThread1(obj);  

  37. MyThread2 t2=new MyThread2(obj);  

  38. t1.start();  

  39. t2.start();  

  40. }  

  41. }  

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including the following −

  • An applet is a Java class that extends the java.applet.Applet class.

  • A main() method is not invoked on an applet, and an applet class will not define main().

  • Applets are designed to be embedded within an HTML page.

  • When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.

  • A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.

  • The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.

  • Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.

  • Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

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.

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java −

import java.applet.*;

import java.awt.*;


public class HelloWorldApplet extends Applet {

   public void paint (Graphics g) {

      g.drawString ("Hello World", 25, 50);

   }

}

These import statements bring the classes into the scope of our applet class −

  • java.applet.Applet

  • java.awt.Graphics

Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to.


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 figure is described in the surrounding text.


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 figure is described in the surrounding text.


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

The figure is described in the surrounding text.

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.



APPLET SKELETON

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.


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

 }

}


applet example

Running Applet using Applet Viewer

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



HTML <applet> tag (Not supported in HTML5)

HTML <applet> tag was used to embed the Java applet in an HTML document. This element has been deprecated in HTML 4.0 and instead of it we can use <object> and newly added element <embed>.

The use of Java applet is also deprecated, and most browsers do not support the use of plugins.

Note: The <applet> tag is deprecated in HTML4.0 and not supported in HTML5. So you can use <object> tag or <embed> tag instead of <applet>.

Syntax

  1. <applet code="URL" height="200" width="100">.............</applet>  

Following are some specifications about <applet> tag

Display

Block

Start tag/End tag

Both Start tag and End tag

Usage

Embed Applets

Example

  1. <!DOCTYPE html>  

  2. <html>  

  3. <head>  

  4.   <title>Applet Tag</title>  

  5.  </head>  

  6.  <body>  

  7.    <p>Example of Applet Tag</p>  

  8.     <applet code="Shapes.class" align="right" height="200" width="300">  

  9.      <b>Sorry! you need Java to see this</b>  

  10.      </applet>  

  11.   </body>  

  12. </html>  

Test it Now


Attributes

Specific Attributes

Attribute name

Value

Description

code

URL

It specifies the URL of Java applet class file.

width

pixels

It specifies the display width of the applet panel.

height

pixels

It specifies the display height of applet panel

align

  • left

  • right

  • top

  • middle

  • bottom

It specifies the position of applet application relative to surrounding content.

alt

text

It is used to display alternative text in case browser does not support Java.

archive

URL

This specifies the archived or compressed version of an applet application.

object

name

It specifies the URL or reference to a serialized representation of an applet.

codebase

URL

It specifies the exact or relative URL of applets .class file specified in the code attribute.

hspace

pixels

It specifies the horizontal space around the applet.

vspace

pixels

It specifies the vertical space around the applet.

name

name

It specifies the name for the applet

Global Attributes

The <applet> tag supports all Global Attributes in HTML

Event Attributes

The <applet> tag supports all Event Attributes in HTML

Supporting Browsers

Element

chrome browser Chrome

ie browser IE

firefox browser Firefox

opera browser Opera

safari browser Safari

<applet>

Not supported

Not Supported

Yes

Not Supported

Yes



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:

  1. public String getParameter(String parameterName)  

Example of using parameter in Applet:

  1. import java.applet.Applet;  

  2. import java.awt.Graphics;  

  3.   

  4. public class UseParam extends Applet{  

  5.   

  6. public void paint(Graphics g){  

  7. String str=getParameter("msg");  

  8. g.drawString(str,50, 50);  

  9. }  

  10.   

  11. }  

myapplet.html

  1. <html>  

  2. <body>  

  3. <applet code="UseParam.class" width="300" height="300">  

  4. <param name="msg" value="Welcome to applet">  

  5. </applet>  

  6. </body>  

  7. </html>  



Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes

Listener Interfaces

ActionEvent

ActionListener

MouseEvent

MouseListener and MouseMotionListener

MouseWheelEvent

MouseWheelListener

KeyEvent

KeyListener

ItemEvent

ItemListener

TextEvent

TextListener

AdjustmentEvent

AdjustmentListener

WindowEvent

WindowListener

ComponentEvent

ComponentListener

ContainerEvent

ContainerListener

FocusEvent

FocusListener



Steps to perform Event Handling

Following steps are required to perform event handling:

  1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For example:

  • Button

    • public void addActionListener(ActionListener a){}

  • MenuItem

    • public void addActionListener(ActionListener a){}

  • TextField

    • public void addActionListener(ActionListener a){}

    • public void addTextListener(TextListener a){}

  • TextArea

    • public void addTextListener(TextListener a){}

  • Checkbox

    • public void addItemListener(ItemListener a){}

  • Choice

    • public void addItemListener(ItemListener a){}

  • List

    • public void addActionListener(ActionListener a){}

    • public void addItemListener(ItemListener a){}


Java Event Handling Code

We can put the event handling code into one of the following places:

  1. Within class

  2. Other class

  3. Anonymous class

Java event handling by implementing ActionListener

  1. import java.awt.*;  

  2. import java.awt.event.*;  

  3. class AEvent extends Frame implements ActionListener{  

  4. TextField tf;  

  5. AEvent(){  

  6.   

  7. //create components  

  8. tf=new TextField();  

  9. tf.setBounds(60,50,170,20);  

  10. Button b=new Button("click me");  

  11. b.setBounds(100,120,80,30);  

  12.   

  13. //register listener  

  14. b.addActionListener(this);//passing current instance  

  15.   

  16. //add components and set size, layout and visibility  

  17. add(b);add(tf);  

  18. setSize(300,300);  

  19. setLayout(null);  

  20. setVisible(true);  

  21. }  

  22. public void actionPerformed(ActionEvent e){  

  23. tf.setText("Welcome");  

  24. }  

  25. public static void main(String args[]){  

  26. new AEvent();  

  27. }  

  28. }  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.

What is an ActionEvent?

- An action event is a semantic event which indicates that a component-defined action occurred.


- The ActionListener interface gets this ActionEvent when the event occurs.


- Event like Button pressed is an action event.


- It is defined in 'java.awt.event' package.


- This event is generated when the button is clicked or the item of a list is double clicked.

Declaration of ActionEvent:

public class ActionEvent

extends AWTEvent




Java MouseListener Interface

The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.

Methods of MouseListener interface

The signature of 5 methods found in MouseListener interface are given below:

  1. public abstract void mouseClicked(MouseEvent e);  

  2. public abstract void mouseEntered(MouseEvent e);  

  3. public abstract void mouseExited(MouseEvent e);  

  4. public abstract void mousePressed(MouseEvent e);  

  5. public abstract void mouseReleased(MouseEvent e);  

Java MouseListener Example

  1. import java.awt.*;  

  2. import java.awt.event.*;  

  3. public class MouseListenerExample extends Frame implements MouseListener{  

  4.     Label l;  

  5.     MouseListenerExample(){  

  6.         addMouseListener(this);  

  7.           

  8.         l=new Label();  

  9.         l.setBounds(20,50,100,20);  

  10.         add(l);  

  11.         setSize(300,300);  

  12.         setLayout(null);  

  13.         setVisible(true);  

  14.     }  

  15.     public void mouseClicked(MouseEvent e) {  

  16.         l.setText("Mouse Clicked");  

  17.     }  

  18.     public void mouseEntered(MouseEvent e) {  

  19.         l.setText("Mouse Entered");  

  20.     }  

  21.     public void mouseExited(MouseEvent e) {  

  22.         l.setText("Mouse Exited");  

  23.     }  

  24.     public void mousePressed(MouseEvent e) {  

  25.         l.setText("Mouse Pressed");  

  26.     }  

  27.     public void mouseReleased(MouseEvent e) {  

  28.         l.setText("Mouse Released");  

  29.     }  

  30. public static void main(String[] args) {  

  31.     new MouseListenerExample();  

  32. }  

  33. }  



Java KeyListener Interface

The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three methods.

Interface declaration

Following is the declaration for java.awt.event.KeyListener interface:

  1. public interface KeyListener extends EventListener  

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:

Sr. no.

Method name

Description

1.

public abstract void keyPressed (KeyEvent e);

It is invoked when a key has been pressed.

2.

public abstract void keyReleased (KeyEvent e);

It is invoked when a key has been released.

3.

public abstract void keyTyped (KeyEvent e);

It is invoked when a key has been typed.

Methods inherited

This interface inherits methods from the following interface:

  • java.awt.EventListener

Java KeyListener Example

In the following example, we are implementing the methods of the KeyListener interface.

KeyListenerExample.java

  1. // importing awt libraries  

  2. import java.awt.*;    

  3. import java.awt.event.*;    

  4. // class which inherits Frame class and implements KeyListener interface  

  5. public class KeyListenerExample extends Frame implements KeyListener {    

  6. // creating object of Label class   and TextArea class  

  7.  Label l;    

  8.     TextArea area;    

  9. // class constructor  

  10.     KeyListenerExample() {    

  11.           // creating the label  

  12.         l = new Label();    

  13. // setting the location of the label in frame  

  14.         l.setBounds (20, 50, 100, 20);    

  15. // creating the text area  

  16.         area = new TextArea();    

  17. // setting the location of text area   

  18.         area.setBounds (20, 80, 300, 300);    

  19. // adding the KeyListener to the text area  

  20.         area.addKeyListener(this);  

  21. // adding the label and text area to the frame  

  22.         add(l);  

  23. add(area);    

  24. // setting the size, layout and visibility of frame  

  25.         setSize (400, 400);    

  26.         setLayout (null);    

  27.         setVisible (true);    

  28.     }    

  29. // overriding the keyPressed() method of KeyListener interface where we set the text of the label when key is pressed  

  30.     public void keyPressed (KeyEvent e) {    

  31.         l.setText ("Key Pressed");    

  32.     }    

  33. // overriding the keyReleased() method of KeyListener interface where we set the text of the label when key is released  

  34.     public void keyReleased (KeyEvent e) {    

  35.         l.setText ("Key Released");    

  36.     }    

  37. // overriding the keyTyped() method of KeyListener interface where we set the text of the label when a key is typed  

  38.     public void keyTyped (KeyEvent e) {    

  39.         l.setText ("Key Typed");    

  40.     }    

  41.   // main method  

  42.     public static void main(String[] args) {    

  43.         new KeyListenerExample();    

  44.     }    

  45. }   



Java WindowListener Interface

The Java WindowListener is notified whenever you change the state of window. It is notified against WindowEvent. The WindowListener interface is found in java.awt.event package. It has three methods.

WindowListener interface declaration

The declaration for java.awt.event.WindowListener interface is shown below:

  1. public interface WindowListener extends EventListener  

Methods of WindowListener interface

The signature of 7 methods found in WindowListener interface with their usage are given below:

Sr. no.

Method signature

Description

1.

public abstract void windowActivated (WindowEvent e);

It is called when the Window is set to be an active Window.

2.

public abstract void windowClosed (WindowEvent e);

It is called when a window has been closed as the result of calling dispose on the window.

3.

public abstract void windowClosing (WindowEvent e);

It is called when the user attempts to close the window from the system menu of the window.

4.

public abstract void windowDeactivated (WindowEvent e);

It is called when a Window is not an active Window anymore.

5.

public abstract void windowDeiconified (WindowEvent e);

It is called when a window is changed from a minimized to a normal state.

6.

public abstract void windowIconified (WindowEvent e);

It is called when a window is changed from a normal to a minimized state.

7.

public abstract void windowOpened (WindowEvent e);

It is called when window is made visible for the first time.

Methods inherited by the WindowListener

This interface inherits methods from the EventListener interface.


No comments:

Post a Comment