Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PlainDocument question

Alex Kravets
Ranch Hand
Posts: 476
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class that extends a JTextField. What it does is allow a user to enter only numbers and a period in that field (to mimic currency field). I've added a listener in this class so I know when something is added or deleted from the field, in order to know when a period is removed. The problem is that once I get the character that was just removed, the removeUpdate() method is too slow to capture that number since it calculates the character after it was removed, so all I get is an empty space for the last character. Does anybody have any suggestion for solving this?
Here is the listener:
class MyDocumentListener implements DocumentListener {
final String newline = "\n";
public void insertUpdate(DocumentEvent e) {
updateLog(e, "inserted");
public void removeUpdate(DocumentEvent e) {
updateLog(e, "removed");
Document doc = (Document)e.getDocument();
String val = "0";
val = doc.getText(((doc.getEndPosition()).getOffset())-1,1);
catch(BadLocationException ble){ble.printStackTrace();}
System.out.println("value: " + val);
isPeriodEntered = false;
public void changedUpdate(DocumentEvent e) {
//Plain text components don't fire these events.
public void updateLog(DocumentEvent e, String action) {
Document doc = (Document)e.getDocument();
int changeLength = e.getLength();
System.out.println(changeLength + " character"
+ ((changeLength == 1) ? " " : "s ")
+ action + newline + "text lenth: " + doc.getLength() + newline);

  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic