Java examples for Swing:JTextComponent
Modifying Text in a JTextComponent
import javax.swing.JTextField; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; public class Main { public static void main(String[] args) throws Exception { // Create the text component JTextComponent textComp = new JTextField("Initial Text"); Document doc = textComp.getDocument(); try {//from w w w . ja v a 2s . co m // Insert some text at the beginning int pos = 0; doc.insertString(pos, "some text", null); // Insert some text after the 5th character pos = 5; doc.insertString(pos, "some text", null); // Append some text doc.insertString(doc.getLength(), "some text", null); // Delete the first 5 characters pos = 0; int len = 5; doc.remove(pos, len); // Replace the first 3 characters with some text pos = 0; len = 3; doc.remove(pos, len); doc.insertString(pos, "new text", null); } catch (BadLocationException e) { } } }