analytics

miércoles, 12 de abril de 2017

Validar JTextField cambiando su color



Vamos a ver como hacer unos métodos estáticos muy simples que nos permitirán validar campos de Java  Swing tipo JTextField. Nos devolverán un booleano indicando si valida, y además, cambiarán el color de fondo del JTextField.

No hay mucho más que comentar, a continuación el código


    public static final Color COLOR_RIGHT = Color.WHITE;
    public static final Color COLOR_ERROR = new Color(255,153,153);
    
    
    public static boolean validateTextField(JTextField textField){
        if (textField.getText()!=null && !"".equalsIgnoreCase(textField.getText())) {
            textField.setBackground(COLOR_RIGHT);
            return true;
        }
        textField.setBackground(COLOR_ERROR);
        return false;
    }
    
    
    public static boolean validateEmailTextField(JTextField textField){
        if (textField.getText()!=null && !"".equalsIgnoreCase(textField.getText())) {
            
            String text = textField.getText();
            if (text.contains("@") && text.contains(".")){
                textField.setBackground(COLOR_RIGHT);
                return true;
            } else {
                textField.setBackground(COLOR_ERROR);
                return false;
            }
        }
        textField.setBackground(COLOR_ERROR);
        return false;
    }
    
    
    public static boolean validateDoubleField(JTextField textField){
        if (textField.getText()==null || "".equalsIgnoreCase(textField.getText())) {
            textField.setBackground(COLOR_ERROR);
            return false;
        }
        
        try {
            Double d = Double.parseDouble(textField.getText());
            textField.setBackground(COLOR_RIGHT);
            return true;
        } catch (Exception e){            
            textField.setBackground(COLOR_ERROR);
            return false;
        }
    }