1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
|
package udfs;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFormattedTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
/**
* choisit la taille et l'activation (par 0 ou 1) d'un controle saisie sur chiffre
*
* @author ec (basé sur le travail d'oma (developpez.com))
*
*/
public class JTextField_MaxLength extends JFormattedTextField implements FocusListener{
private static final long serialVersionUID = 1L;
/**
* @author ec
*
*@param int maxLength
*@param int controle Saisie 0= rien, 1= chiffre
*
*/
public JTextField_MaxLength(int maxLength,int controleSaisie)
{
super();
init();
AbstractDocument doc = (AbstractDocument) getDocument();
doc.setDocumentFilter(new TextLimiter(maxLength,controleSaisie));
}
/**
* do some additional initialisation
*/
private void init()
{
addFocusListener( this );
}
/**
* setText selects when this is used in a table
*/
public void setText(String text)
{
super.setText(text);
selectAll();
}
/**
* focus selects when this is used in a regular form
* but should not select if something was already selected with setText
*/
public void focusGained(FocusEvent e)
{
if (getSelectionStart() == 0 && getSelectionEnd() == 0) selectAll();
}
public void focusLost(FocusEvent e) {
}
/**
* 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;
private int ctrlSaisie;
public TextLimiter(int max,int ctrlSaisie) {
this.max = max;
this.ctrlSaisie = ctrlSaisie;
}
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();
boolean toutOk=true;
System.out.println("new length "+newLength+" et max "+max);
if (newLength <= max) {
// controle saisie chiffre uniquement
if (ctrlSaisie==1)
{
if (UtilitairesDivers.isNumeric(str)==false)
{
toutOk=false;
}
}
}
else
{
toutOk=false;
}
if (toutOk==true)
{
fb.replace(offset, length, str, attrs);
}
else
{
Toolkit.getDefaultToolkit().beep();
}
}
}
} |
Partager