Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

JTextField: limiter à 1 caractère

1 réponse
Avatar
julien
Bonjour
Peut-on facilement limiter le contenu d'un JTextField à 1 seul
caractère. J'ai construit un JTextField d'une taille de A 'new
JTextField(1)), mais on peut en fait rentrer plusieurs caratères dans le
champs.

Merci
Julien

1 réponse

Avatar
Philippe DE RIVAROLA
Bonjour,

Essaie de mettre une instance de cette classe de document dans ton text
field,
avec une longueur max a 1 :

public class LimitedSizeDocument extends PlainDocument
{
/**
* A constant specifying a length of 'unlimited.'
*/
public static final int NO_LIMIT = 0;

/**
* the max length of this document
*/
private int maxLength = NO_LIMIT;

/** Set the maximum length that this document is allowed to have. The
* default length is <code>NO_LIMIT</code>, which means unlimited length.
*
* @param length The new maximum length for the document. If the document
* is currently longer than this length, the excess characters are
deleted.
* The constant <code>NO_LIMIT</code> may be passed to specify unlimited
* length.
*/
public void setMaximumLength(int length)
{
maxLength = ((length < 0) ? 0 : length);

if (maxLength != NO_LIMIT)
{
truncate();
}
}

/**
* Get the current maximum length for this document.
*
* @return The current maximum length, or <code>NO_LIMIT</code> if the
* length is unlimited.
*/
public int getMaximumLength()
{
return (maxLength);
}

/**
* Overridden to constrain document length.
*/
public void insertString(int offset, String string, AttributeSet a)
throws BadLocationException
{
if (maxLength == NO_LIMIT)
{
super.insertString(offset, string, a);
}

else if (maxLength == getLength())
{
Toolkit.getDefaultToolkit().beep();
}

else
{
super.insertString(offset, string, a);
truncate();
}
}

// Truncate excess length
private void truncate()
{
int excess = getLength() - maxLength;
if (excess > 0)
{
try
{
remove(maxLength, excess);
}
catch (BadLocationException ex)
{
}
}
}
}

Philippe