Click to See Complete Forum and Search --> : keyTyped method


Christa
04-17-2005, 06:48 PM
I am a newbe to the Java world, and am having trouble with the processing of the keyTyped event. I get the event ok, but when I get the event, it has not (evidently) been processed and the key placed in the associated textbox. How do I envoke the default processing for the key in the keyTyped event so that I can then perform a getText on the control and get the previous contents *and* the newly typed key?

Khalid Ali
04-17-2005, 11:06 PM
something like this will be good to start you in the irection...


import javax.swing.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.*;


/**
* Created by IntelliJ IDEA.
* User:
* Date: Apr 17, 2005
* Time: 5:09:10 PM
*/
public class KeyEvents extends JFrame implements KeyListener {
JTextField tfTypeIn,tfTypedIn;
JLabel lblTypeText,lblDisplayText;

/**
*
*/
public KeyEvents(){
this.setSize(200,200);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container c = this.getContentPane();
c.add(getAdminPanel());
this.show();
}

/**
*
* @return
*/
public JPanel getAdminPanel(){
tfTypeIn = new JTextField(10);
tfTypeIn.addKeyListener(this);
tfTypedIn = new JTextField(10);
lblTypeText = new JLabel("Type in letters");
lblDisplayText = new JLabel("You typed ");

JPanel pnlAdmin = new JPanel();
pnlAdmin.setLayout(new FlowLayout());

pnlAdmin.add(lblTypeText);
pnlAdmin.add(tfTypeIn);

pnlAdmin.add(lblDisplayText);
pnlAdmin.add(tfTypedIn);

return pnlAdmin;
}

/**
* Empty implementation
* @param e
*/
public void keyTyped(KeyEvent e){}

/**
* Empty implementation
* @param e
*/
public void keyPressed(KeyEvent e){}

/**
* Copies text from the text field where its being typed to one below.
* @param e
*/
public void keyReleased(KeyEvent e){
if(e.getSource()==tfTypeIn){
tfTypedIn.setText(tfTypeIn.getText());
}
}

/**
*
* @param args
*/
public static void main(String[] args){
new KeyEvents();
}
}