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
|
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
/**
* Created by IntelliJ IDEA.
* User: bebe
* Date: 22-mars-2007
*/
public class MyDocumentFilter extends DocumentFilter {
int maxLength = 0;
public MyDocumentFilter(int maxLength) {
// super(); //To change body of overridden methods use File | Settings | File Templates.
this.maxLength = maxLength;
}
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
super.remove(fb, offset, length); //To change body of overridden methods use File | Settings | File Templates.
}
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
replace(fb, offset, 0, string, attr); //To change body of overridden methods use File | Settings | File Templates.
}
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
// super.replace(fb, offset, length, text, attrs); //To change body of overridden methods use File | Settings | File Templates.
int newLength = fb.getDocument().getLength() - length + text.length();
if (newLength <= maxLength) {
fb.replace(offset, length, text.toUpperCase(), attrs);
} else {
throw new BadLocationException("New characters exceeds max size of document", offset);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame myFrame = new JFrame("Limit textComponents with DocumentFilter is better than PlainDocument");
JTextField myTextField = new JTextField();
PlainDocument p = (PlainDocument) myTextField.getDocument();
p.setDocumentFilter(new MyDocumentFilter(25));
myFrame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.insets.left = gbc.insets.right = 5;
gbc.fill = GridBagConstraints.HORIZONTAL;
myFrame.add(myTextField, gbc);
myFrame.setSize(400, 300);
myFrame.setLocationRelativeTo(null);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
});
}
} |
Partager