What I want to do is the moment I pressed the keyboard, whatever is written on the textfield will be shown in the System.out.printLn(). but for every type I make, it will only be shown if I pressed another key.
for example.. I press 'A' ...then a blank space will be shown. I press 'B' ...then 'A' will be shown. I press 'C' ...then 'AB' will be shown.
what I want is if I press 'A' ...then 'A' will be shown...etc is it possible? I also tried this on keyTyped() but the result is just the same..
here is my short code for this...
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class NewClass extends JFrame implements KeyListener{
JTextField tf = new JTextField();
NewClass(){
this.setLayout(null);
tf.setBounds(50, 50, 200, 30);
add(tf);
tf.addKeyListener(this);
}
public static void main(String[] args) {
NewClass r = new NewClass();
r.setVisible(true);
r.setSize(300, 200);
r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(tf.getText());
}
@Override
public void keyReleased(KeyEvent e) {
}
}
Any suggestions? thanks in advance :)
The problem is that keyPressed
is being called before the TextBox is updated.
Instead of
tf.addKeyListener(this);
Try using this:
tf.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
printIt();
}
public void removeUpdate(DocumentEvent e) {
printIt();
}
public void insertUpdate(DocumentEvent e) {
printIt();
}
public void printIt() {
System.out.println(tf.getText());
}
You'll need to import javax.swing.event.DocumentEvent
and javax.swing.event.DocumentListener
.