Table of contents
1.
Introduction 
2.
Java KeyListener
3.
Methods of Java KeyListener
4.
Java KeyListener Examples
4.1.
Example 1
4.2.
Example 2
4.3.
Example 3
5.
Frequently Asked Questions
5.1.
What is Java KeyListener?
5.2.
What are the methods to implement Java KeyListener?
5.3.
Which command does not generate any events?
5.4.
How do you use the KeyReleased method?
5.5.
Why swings are used in Java?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Java KeyListener

Author yuvatimankar
1 upvote

Introduction 

Well, we all have seen interactive applications that perform any function whenever the state of the key is changed. But how do internal things work? How to implement them in Java? To answer all these questions we have Java KeyListener. Java KeyListener is an interface in the java.awt.package and it is useful in interacting with the user whenever the state of the key is changed. 

In this article, we will learn about Java KeyListener, its declaration, and its methods with some detailed examples. So let’s get started with our article.

Also Read About, Multithreading in java and Hashcode Method in Java

Java KeyListener

Java KeyListener is an interface in java.awt.event package. Java KeyListener operates the event whenever the state of the Key is changed. The class that processes the KeyEvent implement the Java KeyListener.Java KeyListener interface consists of 3 Methods.

The following syntax can declare the java KeyListener interface:

public interface KeyListener extends EventListener
You can also try this code with Online Java Compiler
Run Code

Methods of Java KeyListener

Whenever the state of the key is changed, an object must be present in the program, which helps in implementing the interface. An event will be generated by typing the key, pressing the key, or releasing the key; for this, we will use some methods. Java MouseMotionListener consists of three methods, which are as follows:

public abstract void keyPressed(KeyEvent e) It is initiated when a key has been pressed.
public abstract void keyTyped(KeyEvent e) It is initiated when a key has been typed.
public abstract void keyReleased(KeyEvent e) It is initiated when a key has been released.

You can also read about the Multiple Inheritance in Java, Fibonacci Series in Java

Java KeyListener Examples

Let us see some examples of Java KeyListener.

Example 1

In this below code, we are generating output that handles Java KeyListener. In this code, we are counting the words we are typing in the output console. In this program, we have created a class called “KeyListenerExample1” that consists of different methods in it that are responsible for the working of Java KeyListener.

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

public class KeyListenerExample1 extends Frame implements KeyListener {    
    Label l;    
    TextArea area;    
 
    KeyListenerExample1() {    
           l = new Label();    
		   l.setBounds (20, 50, 200, 20);    
 		   area = new TextArea();    
		   area.setBounds (20, 80, 300, 300); 
   
          // adding KeyListener to the text area   
		  area.addKeyListener(this);   
 
		 // adding label and text area to frame  
  		 add(l);  
		 add(area);  
  
		// setting size, layout and visibility of frame  
        setSize (400, 400);    
        setLayout (null);    
        setVisible (true);    
    }    
	public void keyPressed(KeyEvent e) {}  
  
    // overriding the keyReleased() method of KeyListener interface   
		public void keyReleased (KeyEvent e) {    
        String text = area.getText();  
  		String words[] = text.split ("\\s");    
		l.setText ("Words: " + words.length + " Characters:" + text.length());    
    }    
    public void keyTyped(KeyEvent e) {}   
 	public static void main(String[] args) {    
        new KeyListenerExample1();    
    }    
}    
You can also try this code with Online Java Compiler
Run Code


Output:

In the above program, as we can see we have used methods to obtain words and characters when we are typing in the output console. Here, as shown above we have typed “Coding Ninjas” and as a result, words and characters are shown in the output.

Read More About, Basics of Java

Example 2

In the below code, we are going to see the state of the key in the output whether the key is typed, pressed, or released and for doing so we have used a class called “KeyListenerExample” in which we have used methods and we have overridden the methods to check the state of the key.

import java.awt.*;    
import java.awt.event.*;    
 
public class KeyListenerExample extends Frame implements KeyListener {    
// creating object of Label class   and TextArea class  
 Label l;    
    TextArea area;    
// class constructor  
    KeyListenerExample() {    
         l = new Label();    
         l.setBounds (20, 50, 100, 20);    
         area = new TextArea();   
         area.setBounds (20, 80, 300, 300);
  
 // adding the KeyListener to the text area  
        area.addKeyListener(this);  


// adding the label and text area to the frame  
        add(l);  
add(area);    
// setting the size, layout and visibility of frame  
        setSize (400, 400);    
        setLayout (null);    
        setVisible (true);    
    }    
// overriding the keyPressed() method of KeyListener interface where we set the text of the label when key is pressed  
    public void keyPressed (KeyEvent e) {    
        l.setText ("Key Pressed");    
    }    
// Overriding the keyReleased() method of KeyListener interface where we set the text of the label when key is released  
    public void keyReleased (KeyEvent e) {    
        l.setText ("Key Released");    
    }    
// Overriding the keyTyped() method of KeyListener interface where we set the text of the label when a key is typed  
    public void keyTyped (KeyEvent e) {    
        l.setText ("Key Typed");    
    }    
  // Main method  
    public static void main(String[] args) {    
        new KeyListenerExample();    
    }    
}   
You can also try this code with Online Java Compiler
Run Code


Output:

In the above output, as we can see we have typed “Coding Ninjas” and with the help of the above program, we can see the state of the key is shown that it is released in the output.

Example 3

In the below code, we are going to see the state of the key in the output whether the key is typed, pressed, or released and for doing so we have used a class called “JavaKeyListenerExample” in which we have used methods and we have written this program without overriding the methods unlike the above example, to check the state of the key.

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class JavaKeyListenerExample implements KeyListener
{
	Label lb1, lbl2, lb;
	TextField tf1;
	Frame fr;
	String s;
	JavaKeyListenerExample()
	{
	//create a frame
		fr = new Frame("KeyEventListener Example");
		lb1= new Label(" Key Events will be displayed based on the actions", Label.CENTER);
		lbl2= new Label();
		lb= new Label();
		tf1 = new TextField(20);
		fr.setLayout(new FlowLayout());
		fr.add(lb1);
		fr.add(tf1);
		fr.add(lbl2);
		tf1.addKeyListener(this);
		fr.setSize(460,250);
		fr.setVisible(true);
	}


	public void keyPressed(KeyEvent ev)
	{
		lbl2.setText("Pressed Key");
	}


	public void keyReleased(KeyEvent ev)
	{
		lbl2.setText(" Released key");
	}
	//events to be done on typing key
	public void keyTyped(KeyEvent ev)
	{
		lbl2.setText("Key is typed");
		//set the visibility as true
	fr.setVisible(true);
	}
	public static void main(String[] args)
	{
		new JavaKeyListenerExample();
	}
}
You can also try this code with Online Java Compiler
Run Code


Output:

In the above output, as we can see we have typed “Coding Ninjas” and with the help of above program, we can see the state of key is shown that it is released in the output.

Try and compile it by yourself on java online compiler.

Frequently Asked Questions

What is Java KeyListener?

The Java KeyListener interface is identified in Java. awt.Java KeyListener is alerted whenever the state of the Key is changed. 

What are the methods to implement Java KeyListener?

The methods to implement Java KeyListener are KeyPresses(KeyEventev): This method will be initiated when Key is pressed. KeyReleased(KeyEventev): This method will be initiated when a key is released. KeyTyped(KeyEventev): This method will be initiated when Key is typed.

Which command does not generate any events?

The command known as TextArea objects does not generate any events.

How do you use the KeyReleased method?

The keyReleased() function is implemented once when you release a key. 

Why swings are used in Java?

Swings are used for creating window-based applications. Swing in Java is part of the Java foundation class, which is platform-independent and lightweight. 

Conclusion

This article extensively discussed Java KeyListener and its different methods. We started with an introduction of Java KeyListener, then saw some of the ways of Java KeyListener, and after that, we have seen some examples of handling Java KeyListener. 

After reading about Java KeyListener, are you not feeling excited to read/explore more articles on the topic of Java? Don’t worry; Coding Ninjas has covered you. To learn, see Introduction to JavaBasics of Java, Why is Java Platform Independent Learn getting started with Java, and Learn OOPs in Java; also, you can enroll in Basics of Java with Data structure and algorithms. Also, you can visit our website, code studio!

You can refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithmsCompetitive Programming, JavascriptSystem Design, and many more; also, if you want to test your competency in coding; you can check out the mock test series and participate in the contests hosted on Coding Ninjas Studio however if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Uber, Microsoft, etc. you must look at the problemsinterview experiences, and interview bundle for placement preparations.

However, you can consider our paid courses to give your career an edge among others.

Do upvote our blogs if you find them engaging and helpful!

Happy learning!

Live masterclass