Java Pgm15

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

Ex No.

25
Date:
Event Handler
Aim:
To write a java program to copy the text using key events in swings.
Source Code:
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:
Javac TextCopied.java
Java TextCopied

Result:
Thus a java program has been written to copy the text using key events.

You might also like