2012-09-05 3 views

답변

2
javax.swing.InputVerifier 

은 대부분의 간단한 작업에 적합합니다. here에서

public class TexFieldValidator extends InputVerifier { 

    String regex; 
    String errorMsg; 
    JDialog popup; 

    public TexFieldValidator(String regex, String errorMsg) { 
     this.regex = regex; 
     this.errorMsg = errorMsg; 
    } 

    @Override 
    public boolean verify(JComponent input) { 
     boolean verified = false; 
     String text = ((JTextField) input).getText(); 
     if (text.matches(regex)) { 
     input.setBackground(Color.WHITE); 
     if (popup != null) { 
      popup.dispose(); 
      popup = null; 
     } 
     verified = true; 
     } else { 
     if (popup == null) { 
      popup = new JDialog((Window) input.getTopLevelAncestor()); 
      input.setBackground(Color.PINK); 
      popup.setSize(0, 0); 
      popup.setLocationRelativeTo(input); 
      Point point = popup.getLocation(); 
      Dimension dim = input.getSize(); 
      popup.setLocation(point.x - (int) dim.getWidth()/2, point.y + (int) dim.getHeight()/2); 
      popup.getContentPane().add(new JLabel(errorMsg)); 
      popup.setUndecorated(true); 
      popup.setFocusableWindowState(false); 
      popup.getContentPane().setBackground(Color.PINK); 
      popup.pack(); 
     } 
     popup.setVisible(true); 
     } 

     return verified; 
    } 
} 

도난 :

는 여기에 내가 다른 일을 기절 하나입니다. 사용

예 :

iDTextField.setInputVerifier(new TexFieldValidator("[a-zA-Z0-9]{3}", "ID must be 3 alphanumerics.")); 
관련 문제