Validação de campo

Boa tarde…

Estou tentando montar uma validação de campo que só aceita números, nisso, estou usando o evento KeyPressed onde quero verificar se o evt.getKeyChar() está contido em 0…9.

Se não estiver, não aparecerá no campo de texto.

Gostaria de saber, como montar if simplificado, sem OR, verificando e o KeyChar está contido em 0…9.

Desde já, agradeço!

Vamos ver se consigo ajudar…

Adicione essa classe em seu código:

import java.text.*;

import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.JTable;


/**
 *  Controls the text being entered into a text field. Only numbers are accepted.
 *  Intended to be used with "textField.addKeyListener(new KeyAdapter())";
 *
 *@author     wferreira
 */
public final class ToolNumericKeyAdapter extends KeyAdapter {
    private int _maxLength = Integer.MAX_VALUE;
    private boolean _allowPoint = false;
    public static final int INTEGER = 1;
    public static final int FLOATING_POINT = 2;

    private Double _upperLimit;
    private Double _lowerLimit;
    private NumberFormat doubleFormat = NumberFormat.getInstance();

    public ToolNumericKeyAdapter(int maxLength) {
        _maxLength = maxLength;
        _allowPoint = true;
    }

    public ToolNumericKeyAdapter(int maxLength, boolean allowPoint) {
        _maxLength = maxLength;
        _allowPoint = allowPoint;
    }


    public void setUpperValueLimit(double limit) {
        _upperLimit = new Double(limit);
    }


    public void setLowerValueLimit(double limit) {
        _lowerLimit = new Double(limit);
    }


  public void keyTyped(KeyEvent e) {
    char typedChar = e.getKeyChar();
    if (!Character.isISOControl(typedChar)) {
      JTextComponent source = (JTextComponent) e.getSource();
      String text = source.getText().trim();
      if ( typedChar != ',' && typedChar !='.' && !Character.isDigit(typedChar) || (text.length() >= _maxLength)) {
        java.awt.Toolkit.getDefaultToolkit().beep();
        e.consume();
        return;
      }
      StringBuffer buffer = new StringBuffer(text);
      if(typedChar == ','){
        try {
          source.getDocument().insertString(
              source.getCaretPosition(), ".", null);
        } catch (BadLocationException ex1) {
        }
        e.consume();
      }else {
        buffer.append(typedChar);
      }
      text = buffer.toString();
      if (text.length() != 0) {
        double val = 0.0;
        try {
          val = doubleFormat.parse(text).doubleValue();
        } catch (ParseException ex) {
          throw new IllegalArgumentException(
              "Should never allow invalid numbers to enter: " + text);
        }
        if ((_upperLimit != null && _upperLimit.doubleValue() < val) ||
            (_lowerLimit != null && _lowerLimit.doubleValue() > val)) {
          java.awt.Toolkit.getDefaultToolkit().beep();
          e.consume();
          return;
        }
      }
    }
  }
}

Para utilá-la basta fazeer assim:

seuTextField.addKeyListener(new ToolNumericKeyAdapter(4, false));

Ou então voce pode adicionar um DocumentListener ao Document do JTextField e validar lá.

Apliquei a classe. Muito obrigada!

Oi,

Ou melhor que isso… Crie uma classe que extends o componente de texto e implemente uma inner-class que extends o PlainDocument (para manipulação do documento), só sobreescreva o método insertString para o desejado.

Tchauzin!

Abri um tópico a dois dias atrás, trata inclusive disso que a jessicabnu precisa: JTextField que aceite somente números.

Quero fazer algo parecido com o que a lina mencionou: extender PlainDocument para controlar JTextField (para valores monetários, datas, somente números, somente letras, etc).

O ViniGodoy tem me ajudado muito no tópico, com algumas dicas preciosas, mas não consegui evoluir muito na solução.

lina e Mark_Ameba (tem uma classe lá que peguei de uma resposta sua), querem dar uma olhada?

O tópico está aqui: Mascaras e Validação em JTextField