How To Add TextBox KeyListener In Java

0
57

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.

  1. import java.awt.event.KeyAdapter;
  2. import java.awt.event.KeyEvent;
  3. 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.

  1. jTextField1.addKeyListener(new KeyAdapter(){
  2. @Override
  3. public void keyPressed(KeyEvent e){
  4.  
  5. if(e.getKeyCode() == KeyEvent.VK_ENTER){
  6. JOptionPane.showMessageDialog(null, "You Pressed the ENTER Key! " + jTextField1.getText());
  7. }
  8. }
  9. });

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:

Facebook Comments
(Visited 60 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here