jtextfield验证不成功不失去焦点

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * 输入验证不成功就不让
 * 文本框失去焦点
 *
 * @author jwang
 * @date 2013.4.22
 */
public class VerifierTest extends JFrame{
   
    public VerifierTest(){
        JTextField tf1 = new JTextField("Type \"pass\"here");
        getContentPane().add(tf1,BorderLayout.NORTH);
        tf1.setInputVerifier(new PassVerifier());
       
        JTextField tf2 = new JTextField("TextField2");
        getContentPane().add(tf2,BorderLayout.SOUTH);
       
        WindowListener l = new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        };
        addWindowListener(l);
    }
   
    class PassVerifier extends InputVerifier{
        @Override
        public boolean verify(JComponent input){
            JTextField tf = (JTextField)input;
            return "pass".equals(tf.getText());
        }
    }
   
    public static void main(String[] args) {
        JFrame f = new VerifierTest();
        f.pack();
        f.setVisible(true);
    }
   
}

你可能感兴趣的:(jtextfield验证不成功不失去焦点)