¿Cómo limitar el número de caracteres ingresados en un JTextField?¿Cómo limitar el número de caracteres en JTextField?
Supongamos que quiero ingresar, por ejemplo, 5 caracteres máx. Después de eso, no se pueden ingresar caracteres en él.
¿Cómo limitar el número de caracteres ingresados en un JTextField?¿Cómo limitar el número de caracteres en JTextField?
Supongamos que quiero ingresar, por ejemplo, 5 caracteres máx. Después de eso, no se pueden ingresar caracteres en él.
http://www.rgagnon.com/javadetails/java-0198.html
import javax.swing.text.PlainDocument
public class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
Entonces
import java.awt.*;
import javax.swing.*;
public class DemoJTextFieldWithLimit extends JApplet{
JTextField textfield1;
JLabel label1;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
getContentPane().add(label1);
getContentPane().add(textfield1);
textfield1.setDocument
(new JTextFieldLimit(10));
}
}
(primer resultado de Google)
Serán bienvenidos algunos comentarios más para explicar la respuesta. – jfpoilpret
no hay una función directa como textfield.maximumlimit (10); –
No, y le dice que use una clase que amplíe 'PlainDocument' en el javadoc para' JTextField' http://download.oracle.com/javase/6/docs/api/javax/swing/JTextField.html –
Si quieres tener todo en una única pieza de código, a continuación, se puede mezclar respuesta de Tim con la El enfoque del ejemplo se encuentra en la API para JTextField, y obtendrá algo como esto:
public class JTextFieldLimit extends JTextField {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
}
Luego no hay necesidad de agregar un documento al JTextFieldLimit debido a que JTextFieldLimit ya tiene la funcionalidad dentro.
FYI Desde Java 1.4, ya no es necesario y le recomendó que utilice el 'Documento' para esta funcionalidad, en su lugar use' DocumentFilter', vea [Implementación de un Filtro de documento] (http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) y [Ejemplos de DocumentFilter] (http://www.jroller.com/dpmihai/entry/documentfilter) para obtener más información – MadProgrammer
Lea la sección del tutorial de Swing en Implementing a DocumentFilter para obtener una solución más actual.
Esta solución funcionará con cualquier documento, no solo con PlainDocument.
Esta es una solución más actual que la aceptada.
Intenta esto:
textfield.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
getToolkit().beep();
evt.consume();
}
}
});
FYI Desde Java 1.4, ya no es necesario y se recomienda que utilice el 'Documento' para esta funcionalidad, en su lugar use un 'DocumentFilter', vea [Implementando un Filtro de documentos] (http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) y [Ejemplos de DocumentFilter] (http://www.jroller.com/dpmihai/entry/documentfilter) para más detalles, 'KeyListener' nunca es una buena idea con los componentes de texto – MadProgrammer
import java.awt.KeyboardFocusManager;
import javax.swing.InputVerifier;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
/**
*
* @author Igor
*/
public class CustomLengthTextField extends JTextField {
protected boolean upper = false;
protected int maxlength = 0;
public CustomLengthTextField() {
this(-1);
}
public CustomLengthTextField(int length, boolean upper) {
this(length, upper, null);
}
public CustomLengthTextField(int length, InputVerifier inpVer) {
this(length, false, inpVer);
}
/**
*
* @param length - maksimalan length
* @param upper - turn it to upercase
* @param inpVer - InputVerifier
*/
public CustomLengthTextField(int length, boolean upper, InputVerifier inpVer) {
super();
this.maxlength = length;
this.upper = upper;
if (length > 0) {
AbstractDocument doc = (AbstractDocument) getDocument();
doc.setDocumentFilter(new DocumentSizeFilter());
}
setInputVerifier(inpVer);
}
public CustomLengthTextField(int length) {
this(length, false);
}
public void setMaxLength(int length) {
this.maxlength = length;
}
class DocumentSizeFilter extends DocumentFilter {
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
throws BadLocationException {
//This rejects the entire insertion if it would make
//the contents too long. Another option would be
//to truncate the inserted string so the contents
//would be exactly maxCharacters in length.
if ((fb.getDocument().getLength() + str.length()) <= maxlength) {
super.insertString(fb, offs, str, a);
}
}
public void replace(FilterBypass fb, int offs,
int length,
String str, AttributeSet a)
throws BadLocationException {
if (upper) {
str = str.toUpperCase();
}
//This rejects the entire replacement if it would make
//the contents too long. Another option would be
//to truncate the replacement string so the contents
//would be exactly maxCharacters in length.
int charLength = fb.getDocument().getLength() + str.length() - length;
if (charLength <= maxlength) {
super.replace(fb, offs, length, str, a);
if (charLength == maxlength) {
focusNextComponent();
}
} else {
focusNextComponent();
}
}
private void focusNextComponent() {
if (CustomLengthTextField.this == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
}
}
}
Muy buena pregunta, y es raro que las herramientas Swing no incluye esta funcionalidad de forma nativa para JTextFields. Pero, he aquí una gran respuesta de mi curso Udemy.com "aprender Java como un niño":
txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3) // limit textfield to 3 characters
e.consume();
}
});
Esto limita el número de caracteres en un campo de texto juego de adivinanzas a 3 caracteres, reemplazando el caso keyTyped y la comprobación para ver si el campo de texto ya tiene 3 caracteres; si es así, está "consumiendo" el evento clave (e) para que no se procese como lo hace normalmente.
He resuelto este problema utilizando el segmento de código siguiente:
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
boolean max = jTextField1.getText().length() > 4;
if (max){
evt.consume();
}
}
no funciona si el usuario" engaña "con copiar y pegar – Ewoks
Aunque el uso de un documento personalizado va a funcionar, el enfoque preferido para esta solución es utilizar ya sea JFormattedTextField o utilizar un DocumentFilter. Estas son ambas características que se han agregado al JDK en la versión 1.3, creo. El tutorial de Swing cubre ambos enfoques (e incluso eliminó el enfoque de Documento personalizado del tutorial). – camickr
FYI Desde Java 1.4, ya no es necesario y se recomienda que utilice el 'Documento' para esta funcionalidad, en su lugar use' DocumentFilter', consulte [Implementación de un Filtro de documentos] (http://docs.oracle.com/javase) /tutorial/uiswing/components/generaltext.html#filter) y [Ejemplos de DocumentFilter] (http://www.jroller.com/dpmihai/entry/documentfilter) para obtener más detalles – MadProgrammer