2012-03-13 16 views
6

Me gustaría validar la entrada de números en el cuadro de texto.Validación en texto swt

Quiero que el usuario ingrese solo un entero, decimal en el cuadro entre los valores máximo y mínimo.

¿Cómo me puedo asegurar de esto?

Gracias.

Respuesta

3

Puede registrar un ModifyListener con el control de texto y usarlo para validar el número.

txt.addModifyListener(new ModifyListener() { 

     @Override 
     public void modifyText(ModifyEvent event) { 
      String txt = ((Text) event.getSource()).getText(); 
      try { 
       int num = Integer.parseInt(txt); 
       // Checks on num 
      } catch (NumberFormatException e) { 
       // Show error 
      } 
     } 
    }); 

También podría usar addVerifyListener para evitar el ingreso de ciertos caracteres. En el evento pasado a ese método, hay un campo "doit". Si configura eso en falso, impide la edición actual.

11

Utilice un VerifyListener ya que se encargará de pasta, de retroceso, reemplazar .....

P. ej validación

text.addVerifyListener(new VerifyListener() { 
    @Override 
    public void verifyText(VerifyEvent e) { 
    final String oldS = text.getText(); 
    final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end); 

    try { 
     BigDecimal bd = new BigDecimal(newS); 
     // value is decimal 
     // Test value range 
    } catch (final NumberFormatException numberFormatException) { 
     // value is not decimal 
     e.doit = false; 
    } 
    } 
}); 
+0

expresiones parciales como "4e" se debe permitir que sea capaz de entrar en "4e-3" – Stefan

3

entero en SWT

text = new Text(this, SWT.BORDER); 
text.setLayoutData(gridData); 
s=text.getText(); 
this.setLayout(new GridLayout()); 
text.addListener(SWT.Verify, new Listener() { 
    public void handleEvent(Event e) { 
     String string = e.text; 
     char[] chars = new char[string.length()]; 
     string.getChars(0, chars.length, chars, 0); 
     for (int i = 0; i < chars.length; i++) { 
     if (!('0' <= chars[i] && chars[i] <= '9')) { 
      e.doit = false; 
      return; 
     } 
     } 
    } 
}); 
0

tratar el siguiente código:

/** 
* Verify listener for Text 
*/ 
private VerifyListener verfyTextListener = new VerifyListener() { 
    @Override 
    public void verifyText(VerifyEvent e) { 
     String string = e.text; 
     Matcher matcher = Pattern.compile("[0-9]*+$").matcher(string); 
     if (!matcher.matches()) { 
      e.doit = false; 
      return; 
     } 
    } 
}; 
0
  • Si sólo desea permitir que los valores enteros se puede usar un Spinner en lugar de un texto campo.

  • Para la validación de valores dobles, debe tener en cuenta que caracteres como E pueden incluirse en dobles y que la entrada parcial como "4e-" debe ser válida al escribir. Tales expresiones parciales darán una NumberFormatException para Double.parseDouble (partialExpression)

  • Véase también mi respuesta al siguiente pregunta relacionada: How to set a Mask to a SWT Text to only allow Decimals

0

1.Create una clase utill implementar verificar oyente

2.supride el método de verificación de texto

3.implemente su lógica

4.Cree un objeto de la clase utill en la que desea utilizar verificar oyente (en el texto)

5.text.addverifylistener (utillclassobject)

Ejemplo: - clase 1. utill: -

public class UtillVerifyListener implements VerifyListener { 

@Override 
public void verifyText(VerifyEvent e) { 

    // Get the source widget 
    Text source = (Text) e.getSource(); 

    // Get the text 
    final String oldS = source.getText(); 
    final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end); 

    try { 
     BigDecimal bd = new BigDecimal(newS); 
     // value is decimal 
     // Test value range 
    } catch (final NumberFormatException numberFormatException) { 
     // value is not decimal 
     e.doit = false; 
    } 
} 

2.uso de verifylistener en otra clase

public class TestVerifyListenerOne { 
public void createContents(Composite parent){ 

    UtillVerifyListener listener=new UtillVerifyListener(); 
    textOne = new Text(composite, SWT.BORDER); 
    textOne .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); 
    textOne .addVerifyListener(listener) 

    textTwo = new Text(composite, SWT.BORDER); 
    textTwo .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); 
    textTwo .addVerifyListener(listener); 

}}

0
text.addVerifyListener(new VerifyListener() { 
    @Override 
    public void verifyText(VerifyEvent e) { 
     Text text = (Text) e.getSource(); 

     final String oldS = text.getText(); 
     String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end); 

     boolean isValid = true; 

     try { 

      if(! "".equals(newS)){ 
       Float.parseFloat(newS); 
      } 

     } catch (NumberFormatException ex) { 
      isValid = false; 
     } 

     e.doit = isValid; 
    } 
});