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. Advertisements

  2. Steven J Sobol

    Chris Smith Guest

    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. Advertisements

  3. 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

    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.
     
    Roedy Green, Apr 29, 2004
    #4
  5. Just for curiosity, why doesn't JFormattedTextField work for your task?

    /Thomas
     
    Thomas Weidenfeller, Apr 29, 2004
    #5
  6. 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

    mromarkhan 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.
     
    mromarkhan, Apr 30, 2004
    #7
  8. 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. This depends on the formatter. E.g. MaskFormatter installs a
    DocumentFilter to restrict character input.

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

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.