Reputation: 17
I have a textfield, and i want to validate the textfield's input while i'm typing in. Just like the google register form. I tried to use thread. But it looks like a mess.
Upvotes: 1
Views: 2155
Reputation: 596
You can use KeyListener for this TextField.
This is example:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class JtextField {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f= new JFrame("TextField Example");
JTextField t1;
t1=new JTextField("Welcome, Give me a world");
t1.setBounds(50,100, 200,30);
f.add(t1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
t1.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("keyTyped");
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("keyReleased");
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("keyPressed");
}
});
}
}
Upvotes: 0
Reputation: 17464
I have a textfield, and i want to validate the textfield's input while i'm typing in. Just like the google register form. I tried to use thread. But it looks like a mess.
You don't have to use a thread to check the input as you type. You can use the DocumentListener that is implemented for this purpose.
It can listen to the changes in the textfield as you type in the textfield, i.e. type characters / remove characters.
Upvotes: 2