Pesquisar neste blog

segunda-feira, 13 de junho de 2011

Aplicando UpperCase a JTextField

Para forçar a digitação apenas de letras maiúsculas em jTextField, pode ser usado o seguinte código abaixo:




package br.com.claupers.model;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;


public class meuJTextField extends JTextField{
   
    public meuJTextField()
    {       
            
        DocumentFilter filter = new UpperCaseField();
        ((AbstractDocument) this.getDocument()).setDocumentFilter(filter);
       
    }


}
class UpperCaseField extends DocumentFilter {
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text,
            AttributeSet attr) throws BadLocationException {
        if (text!= null)
        fb.insertString(offset, text.toUpperCase(), attr);
    }

    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
            AttributeSet attrs) throws BadLocationException {
        if (text!= null){
        fb.replace(offset, length, text.toUpperCase(), attrs);
        }else {fb.replace(offset, length,null, attrs);}
    }
} 

Para usar o código acima, basta criar seu componente com o seguinte comando:
private JTextField seuField;
seuField = new meuJTextField();

Seria isso.

Cordialmente;



Claudir Pereira dos Santos

Matelândia, 12 de maio de 2011.

Referêcia:

http://www.java2s.com/Code/Java/Swing-JFC/FormatJTextFieldstexttouppercase.htm

2 comentários: