KeyEvent Example
package gui;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class GUIKeyEventExample extends JFrame implements KeyListener{
private JTextArea ta1, ta2;
private JScrollPane sp1, sp2;
public GUIKeyEventExample() {
ta1 = new JTextArea(10,30);
ta2 = new JTextArea(10,40);
sp1 = new JScrollPane(ta1);
sp2 = new JScrollPane(ta2);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(400,400);
ta1.addKeyListener(this);
add(sp1) ; add(sp2);
}
public void keyPressed(KeyEvent ke) {
char mykey = ke.getKeyChar();
if (ke.getKeyCode()==KeyEvent.VK_BACK_SPACE)
{
String ntext = ta1.getText().substring(0,ta1.getText().length()-1);
ta2.setText(ntext);
}
else {
ta2.append(String.valueOf(mykey));
}
}
public void keyReleased(KeyEvent ke) {
}
public void keyTyped(KeyEvent ke) {
// System.out.println("key typed.");
}
public static void main(String[] args) {
new GUIKeyEventExample();
}
}
Comments
Post a Comment