Today’s Tutorial is all about How To Add TextBox KeyListener In Java.
This tutorial will teach you on how to add TextBox keyListener in Java. There are two types of listener commonly used in Java programming, the MouseListener and the KeyListener. The MouseListener is use to detect the activity of your mouse listening what part of the mouse you are clicking. The KeyListener is also use to detect the activity of your keyboard listening what keys you are pressing in the keyboard.
This tutorial will focus on KeyListener and add it to a TextBox element. It means that the KeyListener can only detect the activity of your keyboard if you type in to the TextBox field. This is very helpful to your program especially in your search functions, the search result will display after hitting the Enter key.
How to add TextBox keyListener in Java
Add or create a new form inside your Java source package. In my case, I named my form using “AddTextboxKeyListener”.
Design your form just look like the image below. The uses textfield and label element located from your Netbeans Tool Palette.
Insert the following codes below to access the required libraries needed in this program. The program uses KeyAdapter, KeyEvent, and JOptionPane libraries.
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import javax.swing.JOptionPane;
Insert the following codes below inside your public method after the “initComponents()”. The initComponent is a method that loads the entire constructor to draw the element of your form.
Run your program and the output should look like the image below.
The KeyListener is setup to ENTER key, it means that if you hit the ENTER key in your keyboard, a dialog box appear saying that you hit the ENTER Key. If you have questions and suggestions about this tutorial, feel free to contact us.
Related Articles You May Like:
- Avoid Closing the Form in Java
- How to Play MP3 Music in Java
- Display Data from Selected Table Row to another Form in Java
- Create a Login Form in Java
- VAT Sales Receipt Calculator in Java