Reputation: 295
I'm currently working with getting a phone number from a JtextField, the problem i'm having is that after three digits are entered I want to add a "-" after the third integer is added then another "-" after the sixth integer is added. I'm not exactly sure how to do this. So far I am only checking the digits and making sure they are numbers. I'm pretty sure i should add something here,
homeNum.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
String homeValue = homeNum.getText();
if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || e.getKeyChar() == '-' || e.getKeyChar() == '\b') {
homeNum.setEditable(true);
message.setText("");
}
else {
homeNum.setEditable(false);
message.setText("* Enter only numeric digits(0-9)");
}
}
I was thinking about adding something like this in but the problem is that I can't delete it if I wanted too.
if(homeValue.length()==3)
{
homeNum.setText(homeValue+"-");
}
Anything help/pointers would be greatly appreciated, Thanks.
Upvotes: 2
Views: 301
Reputation: 389
There are plenty of online tutorials to help with this:
public class TextVerifyInputRegularExpression {
/*
* Phone numbers follow the rule
* [(][1-9][1-9][1-9][)][1-9][1-9][1-9][-][1-9][1-9][1-9][1-9]
*/
private static final String REGEX = "[(]\\d{3}[)]\\d{3}[-]\\d{4}"; //$NON-NLS-1$
private static final String template = "(###)###-####"; //$NON-NLS-1$
private static final String defaultText = "(000)000-0000"; //$NON-NLS-1$
public static void main(String[] args) {
A tutorial can be found here
Upvotes: 0
Reputation: 165
Maybe it's an idea to work with different textboxes, like when you fill in a key-code for software-registration.
Upvotes: 0
Reputation: 2003
One way you can do it is this.. You monitor the number of times a key has been pressed. When it gets to 3, you setText to whatever you have there plus a -
Now there are other things to consider like when the backspace has been pressed, you need to subtract one from your counter rather than adding.
Do the same for about 3-4 special keys(like not adding anything when enter is pressed).
You can do these in the background if you have a look at the SwingWorker..
Good luck
Upvotes: 2