Re: how the typed character in a textField will not be printed


2003-08-13 11:01:44 AM
jbuilder3
On 8/10/2003 at 1:15:26 PM, Kostas wrote:
Quote
Hi all, I want to trap the typed characterfrom the user in a
txtField. If the character is not digit it will not be printed in the
componet. I used keytyped event with the folloing code...
char typedChar = e.getKeyChar();
String currText =txtFldMsBdIndxWeight.getText();
if (!Character.isDigit(typedChar))
{
if (currText.length()!=0)
{
currText = currText.substring(0, currText.length()-1);
txtFldMsBdIndxWeight.setText(currText);
}
else txtFldMsBdIndxWeight.setText("");
}

the problem is when the text of the componet is empty
(currText.length()==0) the non digit character will be printed in the
componet the code... txtFldMsBdIndxWeight.setText("");
is not working.
What am i doing wrong thank you for advance,
You are setting the text of the field to "" only when the length of the
field is zero. I would not expect that to have any effect. You have
not done anything that would prevent the JTextField from processing the
KeyEvent, so after you set the field to "" (which it already was), the
JTextField adds the character to the text field.
If you want to replace the processing of a KeyEvent, you would need to
consume() the event when you are done. Otherwise, the event will be
processed normally.
However, I do not think this is really the best approach for solving
your problem. What if someone enters characters into the JTextField
using some mechanism other than a keystroke. For example, the user
might use Control-V or some other keystroke to paste text into the
field. Or he might use a "Paste" menu item to do the deed. Or he
might be using some assistive technology, entering characters with his
voice.
It sounds like you want to control the *characters* that are put into
the field and not react to keystrokes. There are a variety of ways to
do this, depending on which version of Java you are using.
With JDK 1.4, you can use a JFormattedTextField and supply your own
Format or DocumentFilter. If your code needs to work with earlier
versions of Java, then create a custom javax.swing.text.Document (you
can extend AbstractDocument), and override the insertString() method
and possibly the remove() method.
--
Regards,
John McGrath [TeamB]