Home Java Example Java Swing How to handle the text using Key Listener Interface
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

How to handle the text using Key Listener Interface

Advertisement
In this section, you will learn how to handle the text using the key events on the Java Awt component.

How to handle the text using Key Listener Interface

     

In this section, you will learn how to handle the text using the key events on the Java Awt component. All the key events are handled through the KeyListener Interface. In the given example, we are going to show you how to display the text of textField1 on the text field2 on key pressed. 

Given is the description of example code:
In the example, we have create two text fields text1 and text2. When you press the key to write the text on the text1  then you will see the same text will start displaying on the text2. This is possible by using the methods keyPressed() and keyTyped().

Here is the code of TextCopied.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
 
public class TextCopied extends JFrame {
  public TextCopied() throws HeadlessException {
  initComponents();
  }
  protected void initComponents() {
 
  setSize(200200);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
  JLabel label1 = new JLabel("TextField1: ");
  final JTextField text1 = new JTextField();
  JLabel label2 = new JLabel("TextField2: ");
  final JTextField text2 = new JTextField();
  text1.setPreferredSize(new Dimension(10020));
  text2.setPreferredSize(new Dimension(10020));
  getContentPane().add(label1);
  getContentPane().add(text1);
  getContentPane().add(label2);
  getContentPane().add(text2);
 
  text1.addKeyListener(new KeyAdapter() {
  public void keyReleased(KeyEvent e) {
 String text = text1.getText();
  if(text.equals("")){
  System.out.println("Enter the value");
  }
  else{

  text2.setText(text);
  }
  }
  public void keyTyped(KeyEvent e) {
  }
  public void keyPressed(KeyEvent e) {
  }
  });
  }
  public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
  public void run() {
  new TextCopied().setVisible(true);
  }
  });
  }
}

Output will be displayed as:

Download Source Code:

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 14, 2008

Related Tutorials

Ask Questions?    Discuss: How to handle the text using Key Listener Interface  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com