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
| import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import org.apache.log4j.Logger;
/**
* Document with a specified max length.
*
* @author natha
*/
public class ConfigurableDocument extends PlainDocument {
/** The Logger */
private static Logger s_logger = Logger.getLogger(ConfigurableDocument.class);
/** Max length autorized for the document */
private int m_maxLength;
/** Force uppercase ? */
private boolean m_forceUppercase;
/**
* Create a Document with a specified max length.
*
* @param maxLength The maximum length permitted in this document.
*/
public ConfigurableDocument(int maxLength) {
super();
this.m_maxLength = maxLength;
}
/* (non-Javadoc)
* @see javax.swing.text.PlainDocument#insertString(int, java.lang.String, javax.swing.text.AttributeSet)
*/
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
String inputText = str;
if (inputText != null && inputText.length() + getLength() > m_maxLength) {
inputText = inputText.substring(0, inputText.length() - (inputText.length() + getLength() - m_maxLength));
}
if (m_forceUppercase) {
inputText = (inputText != null ? inputText.toUpperCase() : null);
}
super.insertString(offs, inputText, a);
}
/* (non-Javadoc)
* @see javax.swing.text.AbstractDocument#replace(int, int, java.lang.String, javax.swing.text.AttributeSet)
*/
@Override
public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String inputText = text;
if (inputText != null && inputText.length() + getLength() - length > m_maxLength) {
inputText = inputText.substring(0, inputText.length() - (inputText.length() + getLength() - length - m_maxLength));
}
super.replace(offset, length, inputText, attrs);
}
/**
* @return the forceUppercase
*/
public boolean isForceUppercase() {
return this.m_forceUppercase;
}
/**
* @param forceUppercase the forceUppercase to set
*/
public void setForceUppercase(boolean forceUppercase) {
this.m_forceUppercase = forceUppercase;
if (forceUppercase) {
try {
replace(0, getLength(), this.getText(0, getLength()).toUpperCase(), null);
} catch (BadLocationException e) {
s_logger.fatal(e.getMessage(), e);
}
}
}
} |
Partager