Olá amigos,
como que eu poderia fazer um texfield no netbeans so aceita numero e de no maximo 4 caracteres?
Codigo Fonte Netbeans
/*
* limita.java
*
* Created on 28 de Junho de 2007, 12:30
*/
package testes;
/**
*
* @author gggg
*/import java.util.Random;
import java.util.Map.Entry;
public class limita extends javax.swing.JFrame {
/** Creates new form limita */
public limita() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Cdigo Gerado ">
private void initComponents() {
codigo = new javax.swing.JTextField();
codigo.setDocument(new FixedLengthDocument(10));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(159, 159, 159)
.add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 173, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(68, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(90, 90, 90)
.add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(190, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new limita().setVisible(true);
}
});
}
// Declarao de variveis - no modifique
private javax.swing.JTextField codigo;
// Fim da declarao de variveis
}
COdigo que eu copiei aqui no GUJ
[code]
/* FixedLengthDocument.java */
import javax.swing.;
import javax.swing.text.;
public class FixedLengthDocument extends PlainDocument
{
private int iMaxLength;
public FixedLengthDocument(int maxlen)
{
super();
iMaxLength = maxlen;
}
@Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException
{
if (str == null)
return;
if (iMaxLength <= 0) // aceitara qualquer no. de caracteres
{
super.insertString(offset, str, attr);
return;
}
int ilen = (getLength() + str.length());
if (ilen <= iMaxLength) // se o comprimento final for menor...
super.insertString(offset, str, attr); // ...aceita str
else
{
if (getLength() == iMaxLength)
return; // nada a fazer
String newStr = str.substring(0, (iMaxLength - getLength()));
super.insertString(offset, newStr, attr);
}
}
}[/code]