Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 340
  • Last Modified:

Overwritting characters in JTextField

I would like to allow users to overwrite text in my JTextFields on a character by character basis. In other words, if the word cat is in a JTextField and the user puts his cursor in front of the c and types a b, the string would turn to bat.

What's the easiest way to replace text?
0
kmenzel
Asked:
kmenzel
  • 2
1 Solution
 
allieCommented:
As far as I know, the only way to really do what you seem to be asking is to extend the PlainDocument class then assign that to your JTextField.  So you'd have something like this:

class MyDocument extends PlainDocument      
{  
   MyDocument()
   { super(); }

   public void insertString(int offs, String  str, AttributeSet attr) throws BadLocationException
   {
      if (str == null) return;
      //Get the text as it exists before the user changed it
      String originalText = this.getText(0, this.getLength());
      //Get the text as YOU want it - i.e. replacing a character instead of just adding a character
      String newText = originalText.substring(0, offs) + str + originalText.substring(offs+str.length(), origianlText.length());
      //Put your string back into the text box
      super.insertString(0, newText, attr);
   }
}

Note that I haven't tried this exactly, so you may need to include "remove(0, originalText.length());" before the super.insertString() in order to remove existing text before you write your own.  In any case, when you declare your text box, just do this:

JTextField myField = new JTextField();
myField.setDocument(new MyDocument());

That's it!

allie
0
 
objectsCommented:
try:

public void insertString(int offs, String s,
  AttributeSet a) throws BadLocationException
{
  super.remove(off, off+s.length());
  super.insertString(off, s, a);
}
0
 
kmenzelAuthor Commented:
I ended up doing something very similar except that I allow insert or overwrite. Thought I was missing something in the API. I guess not.

Thanks
0
 
objectsCommented:
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now