O processo é muito semelhante ao do FloatField
IntegerField
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* Esta classe permite fazer entrada de valores tipo integer
*
* @author junior
* @version 1.0
*/
public class IntegerField extends JTextField
{
private int maiorLimit;
private static final int MAX_DEFAULT = 999999;
// construtor completo todas as propriedades
public IntegerField(int cols, int amaiorLimit)
{
super(cols);
this.maiorLimit = amaiorLimit;
setHorizontalAlignment(JTextField.RIGHT);
}
// construtor padrão tem que informar pelo menos o cols para definir o tamanho do field
public IntegerField(int cols) {
this(cols, MAX_DEFAULT);
}
// seta limites ao valor máximo e mínino permitidos
public void setLimites(int amaiorLimit)
{
this.maiorLimit = amaiorLimit;
}
// método para obter o valor em formato double
public double getInt()
{
try
{
if (getText().trim().equals("")) return 0;
return Integer.parseInt(getText());
}
catch(NumberFormatException ex)
{
return 0;
}
}
// método para "setar" o valor da JTextField
public void setInt(int valor) {
setText(String.valueOf(valor));
}
// método interno que define qual Document o JTextField usará
protected Document createDefaultModel()
{
return new IntegerDocument();
}
/**
* classe interna LimitDocument
* objetivo: formatar entrada e limitar valores da FloatField
*/
class IntegerDocument extends PlainDocument
{
// método herdado
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
// tem algum valor "entrando"?
if(str != null)
{
try
{
// acrescenta ao texto o digitado numa var local (newStr)
String newStr = getText(0, getLength()) + str;
// converte newStr para int
int i = Integer.parseInt(newStr);
// está dentro dos limites?
if (i <= maiorLimit)
{
super.insertString(offs, str, a); // permite ir para tela
}
}
catch(NumberFormatException ex)
{
// se falhar não faz nada
}
}
}
}
}
Exemplo
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class Geral extends JFrame {
private IntegerField campo1;
private IntegerField campo2;
public Geral() {
setSize(200, 110);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
campo1 = new IntegerField(10); // 10 colunas
campo2 = new IntegerField(10, 3); // 10 colunas: valores aceitos 0-3
add(campo1);
add(campo2);
setVisible(true);
}
public static void main(String[] args) {
new Geral();
}
}