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