I’m trying to create JTextField
that can accept only double (including scientific notation) with this check:
abstract class DoubleKeyAdapter extends KeyAdapter
{
@Override
public void KeyTyped(KeyEvent e)
{
if (!(((JTextField) e.getSource()).getText() + e.getKeyChar()).matches(“[+-]?\\d*(\\.\\d*)?([eE][+-]?\\d*)?”))
e.consume();
}
@Override
public abstract void KeyReleased(KeyEvent e);
}
The problem is when I try to add -
for example to the beggining of the text field. it doesn’t let me do so because it does the checking by appending -
at the end of the text, in other words, I can’t know where the new character had been added.
So my questions are:
- Is there a way to get a preview of the entire text before it is present in the text field?
- Is there a way to create
JTextField
(or extention of it) that does it better? - Is there a way to know the location of the new character?
You can use a
DocumentFilter
for this.It allows you to do editing before the text is inserted into the Document.
It doesn't do everything you want, but it should get you started.