简体   繁体   中英

Validate JTextField while typing in

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.

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, ie type characters / remove characters.

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");
                }
            }); 
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM