Reputation: 59
I've made a JTextField that restricts characters being entered unless it's numbers, letter "e", or comma . But now I realised that it restricts backspace being pressed to. How can I change it? I'll add the code, where it checks what key is being pressed, below
for (JTextField tf : listOfFields)
{
String value = tf.getText();
int n = value.length();
if (ke.getKeyChar()>= '0' && ke.getKeyChar() <= '9' || ke.getKeyChar() == ','|| ke.getKeyChar() == 'e')
{
tf.setEditable(true);
}
else
{
tf.setEditable(false);
}
}}});
Upvotes: 1
Views: 1639
Reputation: 44414
To have a text field accept a numeric entry, you should use a JFormattedTextField:
JFormattedTextField field = new JFormattedTextField(
NumberFormat.getIntegerInstance());
field.setColumns(12);
To make it check both a localized number format (one that uses commas) and also the java.lang syntax (like 1e5
), you can create a NumberFormatter which does both:
NumberFormatter formatter = new NumberFormatter() {
@Override
public Object stringToValue(String text)
throws ParseException {
try {
return Double.valueOf(text);
} catch (NumberFormatException ne) {
return super.stringToValue(text);
}
}
};
JFormattedTextField field = new JFormattedTextField(formatter);
field.setColumns(12);
Each field’s value can be retrieved with the getValue
method:
for (JFormattedTextField tf : listOfFields) {
Number value = (Number) tf.getValue();
// ...
}
Restricting the keys typed by the user is not the correct way to guarantee numeric entry. For instance, your code would allow a user to type 123,4,45,678
.
There are many keys which allow editing. Home, End, Delete, and Ctrl-A are just a few. You shouldn't try to explicitly accommodate them all with a keystroke whitelist. Let JFormattedTextField do the work of verifying the input.
Upvotes: 2
Reputation: 4899
If you really want to stick to this way of filtering, assuming ke is a KeyEvent, test the key code not the key char: add this condition
|| ke.getKeyCode() == KeyEvent.VK_BACK_SPACE
Upvotes: 0