My TextField code:
JTextField txtNumeroDeOrigen = new JTextField();
txtNumeroDeOrigen.setBounds(237, 11, 125, 20);
contentPane.add(txtNumeroDeOrigen);
txtNumeroDeOrigen.setColumns(10);
In that field I request a phone number: ###-###-####. The user enters, example: 7875556666
I would like to have a MaskFormatter, so that it writes to the TextField, example: (787) 555-6666.
So I take advantage and only allow the entry of numbers, and not letters or rare signs.
I've seen examples but they don't work for me. Any simple solution?
Cheers!.
Instead of
JTextField
, you can useJFormattedTextField
* and also an instance ofjavax.swing.text.MaskFormatter
. That is (for example):* To learn more, you can take a look at How to Use Formatted Text Fields within The Java Tutorials .
The Option raised by @Paul is a good one. Use JFormattedTextField to have this mask, but for one
TextField
you could create a class that extends PlainDocument , evaluating through the insertString method according to the format you want to give it.(para el ejemplo (###)###-###. sería)
I would assign the
Document
toTextField
like so:you can use
String.replaceFirst()