LONGUEUR LIMITE D'UN TEXT DANS UN TextField

OUAHID -  
 maxime -
je voudrais limiter le nombre de caractères saisis dans un champ de text avec java (jdk)

4 réponses

  1. djmalo
     
    Pour info cela ne marche pas si on fait un copier-coller d'un texte trop long dans le textfield.

    Il vaut mieux faire ceci :

    import java.awt.Toolkit;

    import javax.swing.JTextField;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DocumentFilter;

    /**
    * TextField that can be limited in size (max number of characters typed in)
    * @author oma
    *
    */
    public class LimitedTextField extends JTextField {

    public LimitedTextField(int maxLength)
    {
    super();
    AbstractDocument doc = (AbstractDocument) getDocument();
    doc.setDocumentFilter(new TextLimiter(maxLength));
    }

    /**
    * Text limiter used to limit the number of characters of text fields
    * Should be used this way :
    *
    * AbstractDocument doc = (AbstractDocument) myTextComponent.getDocument();
    doc.setDocumentFilter(new TextLimiter(maxLength));
    *
    * @author oma
    *
    */
    private class TextLimiter extends DocumentFilter {
    private int max;

    public TextLimiter(int max) {
    this.max = max;
    }

    public void insertString(DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet attr) throws BadLocationException {

    replace(fb, offset, 0, str, attr);
    }

    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String str, AttributeSet attrs) throws BadLocationException {
    int newLength = fb.getDocument().getLength() - length + str.length();

    if (newLength <= max) {
    fb.replace(offset, length, str, attrs);
    } else {
    Toolkit.getDefaultToolkit().beep();
    }
    }
    }

    }
    6
    1. Pumbaa
       
      C'est absolument parfait djmalo !!!
      0
  2. SebastienL Messages postés 11 Statut Membre 65
     
    Ou, si tu tu veux rendre la chose encore plus agréable tu peux limiter toi même avec un listener , tu te fais un petite classe du style :
    public class MonTextField extends JTextField {

    private boolean utilityKeyPressed=false;
    private int maxChar = 10;

    public MonTextField(int max) {
    super();
    maxChar = max;
    this.addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) { checkutilityKey(e); }
    public void keyTyped(KeyEvent e){ checklenght(e); }
    public void keyReleased(KeyEvent e){ e.consume(); }
    }
    );
    }
    /*Vérification des touches BACKSPACE,LEFT,RIGHT pour les gardées actives*/
    private void checkutilityKey(KeyEvent e) {
    utilityKeyPressed = (e.getKeyCode()==e.VK_BACK_SPACE || e.getKeyCode()==e.VK_LEFT || e.getKeyCode()==e.VK_RIGHT || e.getKeyCode()==e.VK_UP || e.getKeyCode()==e.VK_DOWN);

    }

    /*Vérification de la longueur*/
    private void checklenght(KeyEvent e) {
    if(!utilityKeyPressed && this.getText().length()=>maxChar)e.consume();

    }
    }

    Et voilà, tu as une petite class qui t'affiche un JTextfield avec un max de caractère.
    2
  3. Dan
     
    Encore plus simple !

    jTextField.addKeyListener( new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent e) {

    if ( jTextField.getText().length()+1 >= max_length )
    e.consume();
    }
    });
    -2
    1. maxime
       
      pur ceux qui peuvent encore tomber sur ce thread, cette solution est MAUVAISE:
      ce code ne gère pas l' insertion (écrire au milieu du JTextField)
      0
  4. SebastienL Messages postés 11 Statut Membre 65
     
    Si mes souvenires sont bons, en java le constructeur, si tu utilise un JTextField biensur, c'est new JTextField(<String>,<nbr columns>);
    ou
    setColumns(<nbr columns>);

    pour limiter le nbr de colonnes dans le JTextField.
    -3
    1. maxime
       
      et re-FAUX:
      le nombre de colonnes est un indice donné au LayoutManager pour estimer la taille du champ.
      0