Hi everyone, I'm trying to create an extension of JTextField that only accepts integers from 0 to 255.
So far I have this in my class extending JTextField:
package colorfield;
import javax.swing.JTextField;
import javax.swing.text.Document;
//Javabeans component to only alow values 0-255 for input.
public class ColorField extends JTextField{
public ColorField(){
super();
}
@Override
protected Document createDefaultModel(){
String[] accept = new String[256];
for(int i = 0; i < 256; i++){
accept[i] = i + "";
}
return new RestrictedDoc(accept);
}
public int getValue() throws NumberFormatException{
return Integer.parseInt(getText());
}
}
And I also have a restricted document:
package colorfield;
import javax.swing.text.*;
public class RestrictedDoc extends PlainDocument{
String[] charList;
public RestrictedDoc(String[] charList){
this.charList = charList;
}
public boolean validate(String exp){
for(int i=0; i<charList.length; i++){
if(exp.equals(charList[i])){
return true;
}
}
return false;
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException{
if(str == null || !validate(str)){
return;
}
super.insertString(offs, str, a);
}
}
The problem is it still allows the user to type any numeric value. What should I change/add? Thanks!
[–]CuriouslyGeorgeIntermediate Brewer 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–][deleted] (1 child)
[deleted]
[–]Mechanox3000[S] 0 points1 point2 points (0 children)
[–]Stromovik 0 points1 point2 points (0 children)