Filtering?
Hi,
I am trying to implement a filter into a JTextField that would take a range [a-zA-Z0-9_]+ or something similar and restrict user input into the field as they are typing in. I did something similar using a modified Plain Document for integer input but I am stumped as to how I am to restrict input based on a passed range/pattern.
Thanks
[367 byte] By [
avdic] at [2007-9-26 3:50:48]

Will you have a button that you press after entrering the text? If so just take the string and check each chararter for the range. Exactly the same thing that you would have done for the key pressed except you will have a full string and might need to parse it.
String s = "Test String";
for (int i=0; i < s.length(); i ++) {
char c = s.charAt(i);
}
> Try using a PlainDocument with the JTextField.
>
> Make your own class that extends PlainDocument and
> override insertString(...) (this is actually from
> AbstractDocument)
>
> Inside the method, simply check the string being
> inserted.
ok, that wouldn't be a problem if I checked against one pattern all the time. But if I have to check against a-fA-Q0-6 one time and A-Zbac+ the next time, do I need to code a check for each letter? or what?
avdic at 2007-6-29 12:36:35 >

Here's a working example. The textfield accepts
alphanumeric characters and underscores. If the user enters (or pastes) bad characters, it beeps.
// TestFrame.java
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class TestFrame
{
public static void main(String[] args)
{
JFrame jf = new JFrame("FilterTest");
JTextField jt = new JTextField(new FilteredDocument(), null, 25);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(150, 50);
jf.getContentPane().add(jt);
jf.show();
}
}
class FilteredDocument extends PlainDocument
{
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
for (int i = 0; i < str.length(); i++)
{
if (!isAlphaNumOrUnderscore(str.charAt(i)))
{
Toolkit.getDefaultToolkit().beep();
return;
}
}
super.insertString(offs, str, a);
}
public static boolean isAlphaNumOrUnderscore(char ch)
{
if (ch == '_')
{
return(true);
}
if (Character.isDigit(ch))
{
return(true);
}
if (ch >= 'a' && ch <= 'z')
{
return(true);
}
if (ch >= 'A' && ch <= 'Z')
{
return(true);
}
return(false);
}
}
hehe posted at the same time...
I'm not sure about regular expressions in java. I think I searched the API one but couldn't find anything useful.
But if there is, you'd simply check it against the regular expression in the PlainDocument.insertString. Maybe extend PlainDocument to take a regular expression?
I'd post a topic on regular expressions and see if anyone replies.