Easy way to specify all non-alphanumeric characters?

S

Steven J Sobol

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) / (e-mail address removed)
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
 
C

Chris Smith

Steven said:
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
 
S

Steven J Sobol

Chris Smith said:
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) / (e-mail address removed)
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
 
R

Roedy Green

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

Thomas Weidenfeller

Steven said:
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
 
S

Steven J Sobol

Thomas Weidenfeller said:
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) / (e-mail address removed)
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
 
M

mromarkhan

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

Steven J Sobol

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) / (e-mail address removed)
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
 
T

Thomas Weidenfeller

Steven said:
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
 

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top