Easy way to specify all non-alphanumeric characters?

Discussion in 'Java' started by Steven J Sobol, Apr 28, 2004.

  1. I'm creating a control (subclass of JTextField) that handles input of IP
    addresses* and am using a KeyAdapter to restrict input to numeric digits and
    the period key.

    It works really well. Too well, in fact, as keystrokes like backspace that
    aren't valid input characters (but need to be passed) get eaten.

    Is there a way to specify the set of non-alphanumeric keyboard keys without
    having to specify each one's virtual keycode separately? I want to eat
    keystrokes for alphanumeric/symbol keys other than 1234567890 and . but if
    a key is pressed that is not an alphanumeric or symbol key (F1-F12, PgUp,
    PgDn, Enter, Backspace, etc.) I don't want to do anything with it.

    Here's my current code:

    addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
    String validChars="0123456789." ;
    if ( validChars.indexOf(e.getKeyChar())==-1 ) {
    e.consume();
    }
    }
    });

    TIA for whatever advice you can offer.

    --
    JustThe.net Internet & New Media Services, Apple Valley, CA PGP: 0xE3AE35ED
    Steven J. Sobol, Geek In Charge / 888.480.4NET (4638) /
    Domain Names, $9.95/yr, 24x7 service: http://DomainNames.JustThe.net/
    "someone once called me a sofa, but i didn't feel compelled to rush out and buy
    slip covers." -adam brower * Hiroshima '45, Chernobyl '86, Windows 98/2000/2003
    Steven J Sobol, Apr 28, 2004
    #1
    1. Advertising

  2. Steven J Sobol

    Chris Smith Guest

    Steven J Sobol wrote:
    > I'm creating a control (subclass of JTextField) that handles input of IP
    > addresses* and am using a KeyAdapter to restrict input to numeric digits and
    > the period key.
    >
    > It works really well. Too well, in fact, as keystrokes like backspace that
    > aren't valid input characters (but need to be passed) get eaten.


    Indeed. This kind of code belongs in the model, not the event handling
    of the component. You can easily subclass the model to restrict input
    characters.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
    Chris Smith, Apr 28, 2004
    #2
    1. Advertising

  3. Chris Smith <> wrote:
    > Steven J Sobol wrote:
    >> I'm creating a control (subclass of JTextField) that handles input of IP
    >> addresses* and am using a KeyAdapter to restrict input to numeric digits and
    >> the period key.
    >>
    >> It works really well. Too well, in fact, as keystrokes like backspace that
    >> aren't valid input characters (but need to be passed) get eaten.

    >
    > Indeed. This kind of code belongs in the model, not the event handling
    > of the component. You can easily subclass the model to restrict input
    > characters.


    Noted. You can chalk that up to my relative inexperience doing what I'm
    trying to do. ;) Thanks for the tip.

    btw, the footnote that I forgot:

    *I'm aware of the freeware IP address editor that's out there, but I'm
    rolling my own because that other component isn't a JavaBean and I want
    something that I can use in the GUI form designer in NetBeans.

    --
    JustThe.net Internet & New Media Services, Apple Valley, CA PGP: 0xE3AE35ED
    Steven J. Sobol, Geek In Charge / 888.480.4NET (4638) /
    Domain Names, $9.95/yr, 24x7 service: http://DomainNames.JustThe.net/
    "someone once called me a sofa, but i didn't feel compelled to rush out and buy
    slip covers." -adam brower * Hiroshima '45, Chernobyl '86, Windows 98/2000/2003
    Steven J Sobol, Apr 28, 2004
    #3
  4. Steven J Sobol

    Roedy Green Guest

    On Wed, 28 Apr 2004 12:03:49 -0500, Steven J Sobol
    <> wrote or quoted :

    >String validChars="0123456789." ;
    > if ( validChars.indexOf(e.getKeyChar())==-1 ) {


    that's pretty quick though I would use < 0 rather than == -1. An old
    habit from the LGP days when that sort of thing made 5 minutes
    difference in running time. You can also use Character.isNumeric, but
    it lets through some numeric characters you probably have never heard
    of.

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
    Roedy Green, Apr 29, 2004
    #4
  5. Steven J Sobol wrote:
    > I'm creating a control (subclass of JTextField) that handles input of IP
    > addresses* and am using a KeyAdapter to restrict input to numeric digits and
    > the period key.


    Just for curiosity, why doesn't JFormattedTextField work for your task?

    /Thomas
    Thomas Weidenfeller, Apr 29, 2004
    #5
  6. Thomas Weidenfeller <> wrote:
    > Steven J Sobol wrote:
    >> I'm creating a control (subclass of JTextField) that handles input of IP
    >> addresses* and am using a KeyAdapter to restrict input to numeric digits and
    >> the period key.

    >
    > Just for curiosity, why doesn't JFormattedTextField work for your task?


    It appears that JFormattedTextField allows for data validation after the
    control loses the focus, but I am actually restricting characters entered
    into the field as they are typed.

    --
    JustThe.net Internet & New Media Services, Apple Valley, CA PGP: 0xE3AE35ED
    Steven J. Sobol, Geek In Charge / 888.480.4NET (4638) /
    Domain Names, $9.95/yr, 24x7 service: http://DomainNames.JustThe.net/
    "someone once called me a sofa, but i didn't feel compelled to rush out and buy
    slip covers." -adam brower * Hiroshima '45, Chernobyl '86, Windows 98/2000/2003
    Steven J Sobol, Apr 29, 2004
    #6
  7. Steven J Sobol

    Guest

    Peace be unto you.

    Outputs
    Enter an ip address like 12.23.23.233
    Only numbers and period allowed
    Cannot tab out if incorrect format

    Tested using
    SciTE
    jsdk 1.5

    import javax.swing.*;
    import java.awt.*;
    import javax.swing.text.*;
    import java.util.regex.*;
    import java.util.*;
    public class Editor extends JFrame
    {
    public Editor()
    {
    this.setTitle("Discover");
    IPField ipfield = new IPField(12);
    ipfield.setInputVerifier(new IPFieldVerifier());
    this.getContentPane().add(ipfield,BorderLayout.CENTER);
    this.getContentPane().add(new JButton("Port Scan"),BorderLayout.SOUTH);
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    }
    public static void main(String [] args)
    {
    new Editor();
    }

    public class IPFieldVerifier extends InputVerifier
    {
    public boolean verify(JComponent input)
    {
    if (input instanceof JTextField)
    {

    Pattern pattern = Pattern.compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
    Matcher matcher = null;
    JTextField ftf = (JTextField)input;
    String text = ftf.getText();
    matcher = pattern.matcher(text);
    if(matcher.find())
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    return true;
    }

    public boolean shouldYieldFocus(JComponent input)
    {
    return verify(input);
    }
    }



    public class IPField extends JTextField
    {

    public IPField(int cols)
    {
    super(cols);
    }

    protected Document createDefaultModel()
    {
    return new IPDocument();
    }

    class IPDocument extends PlainDocument
    {
    Pattern pattern = Pattern.compile("[\\d\\.]");
    Matcher matcher = null;
    public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException
    {

    if (str == null)
    {
    return;
    }
    matcher = pattern.matcher(str);
    if(!matcher.find())
    {
    return;
    }
    super.insertString(offs, str, a);
    }
    }
    }
    }

    Have a good day.
    , Apr 30, 2004
    #7
  8. wrote:
    >
    > Peace be unto you.
    >
    > Outputs
    > Enter an ip address like 12.23.23.233
    > Only numbers and period allowed
    > Cannot tab out if incorrect format


    Thanks, but I'm restricting what is typed as it is typed... I'll hold on
    to this anyhow, as I'm sure I'll be able to use it somewhere else.
    --
    JustThe.net Internet & New Media Services, Apple Valley, CA PGP: 0xE3AE35ED
    Steven J. Sobol, Geek In Charge / 888.480.4NET (4638) /
    Domain Names, $9.95/yr, 24x7 service: http://DomainNames.JustThe.net/
    "someone once called me a sofa, but i didn't feel compelled to rush out and buy
    slip covers." -adam brower * Hiroshima '45, Chernobyl '86, Windows 98/2000/2003
    Steven J Sobol, Apr 30, 2004
    #8
  9. Steven J Sobol wrote:
    > It appears that JFormattedTextField allows for data validation after the
    > control loses the focus, but I am actually restricting characters entered
    > into the field as they are typed.


    This depends on the formatter. E.g. MaskFormatter installs a
    DocumentFilter to restrict character input.

    /Thomas
    Thomas Weidenfeller, Apr 30, 2004
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. joe

    remove non alphanumeric characters

    joe, Mar 2, 2007, in forum: C Programming
    Replies:
    5
    Views:
    815
  2. Yasin Cepeci
    Replies:
    1
    Views:
    906
    Juan T. Llibre
    Apr 26, 2007
  3. The Web President

    re.match and non-alphanumeric characters

    The Web President, Nov 16, 2008, in forum: Python
    Replies:
    8
    Views:
    372
    John Machin
    Nov 17, 2008
  4. Yasin Cepeci
    Replies:
    2
    Views:
    233
    Yasin Cepeci
    Apr 26, 2007
  5. Theallnighter Theallnighter

    Newbie Question: delete all non alphanumeric characters

    Theallnighter Theallnighter, Jul 21, 2006, in forum: Ruby
    Replies:
    15
    Views:
    289
    Joe Karma
    Jul 22, 2006
Loading...

Share This Page