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(200, 200);
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(100, 20));
text2.setPreferredSize(new Dimension(100, 20));
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: