here's the code that i have on how to limit the character input length
class JTextFieldLimit extends PlainDocument {
private int limit;
// optional uppercase conversion
private boolean toUppercase = false;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
toUppercase = upper;
}
@Override
public void insertString
(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
if (toUppercase) str = str.toUpperCase();
super.insertString(offset, str, attr);
}
}
}
can be implemented by txtSample.setDocument(new JTextFieldLimit(30));
and here's what i have on accepting numeric numbers only(it accepts decimal though w/c i dont need)
class NumericDocument extends PlainDocument {
protected int decimalPrecision = 0;
protected boolean allowNegative = false;
public NumericDocument(int decimalPrecision, boolean allowNegative) {
super();
this.decimalPrecision = decimalPrecision;
this.allowNegative = allowNegative;
}
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str != null){
if (StringFormat.isNumeric(str) == false && str.equals(".") == false && str.equals("-") == false){ //First, is it a valid character?
Toolkit.getDefaultToolkit().beep();
return;
}
else if (str.equals(".") == true && super.getText(0, super.getLength()).contains(".") == true){ //Next, can we place a decimal here?
Toolkit.getDefaultToolkit().beep();
return;
}
else if (StringFormat.isNumeric(str) == true && super.getText(0, super.getLength()).indexOf(",") != -1 && offset>super.getText(0, super.getLength()).indexOf(",") && super.getLength()-super.getText(0, super.getLength()).indexOf(".")>decimalPrecision && decimalPrecision > 0){ //Next, do we get past the decimal precision limit?
Toolkit.getDefaultToolkit().beep();
return;
}
else if (str.equals("-") == true && (offset != 0 || allowNegative == false)){ //Next, can we put a negative sign?
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offset, str, attr);
}
return;
}
public static class StringFormat
{
public StringFormat()
{
}
public static boolean isNumeric(String str)
{
try
{
int x = Integer.parseInt(str);
System.out.println(x); return true;
} catch(NumberFormatException nFE)
{
System.out.println("Not an Integer"); return false;
}
}
}
}
and heres how to use this code: txtSample.setDocument(new NumericDocument(0,false));
now the problem is the txtSample
can only setDocument
once. How do i limit a jtextfield length and accept numbers only at the same time? Or is there any simpler way to do this? Thanks. :D
== true
parts of yourif
coditions, they are redundant. Also, if you want,== false
can be replaced by a!
before the expression. – Dinger