The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextComponent  [11 examples]

e970. Modifying Text in a JTextComponent

    // Create the text component
    JTextComponent textComp = new JTextField("Initial Text");
    Document doc = textComp.getDocument();
    
    try {
        // 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) {
    }
    
    

 Related Examples
e968. Retrieving Text from a JTextComponent
e969. Retrieving All the Text from a JTextComponent Efficiently
e971. Asynchronously Reading the Contents of a Visible JTextComponent
e972. Finding Word Boundaries in a JTextComponent
e973. Retrieving the Visible Lines in a JTextComponent
e974. Using a Position in a JTextComponent
e975. Limiting the Capacity of a JTextComponent
e976. Enabling Text-Dragging on a JTextComponent
e977. Sharing a Document Between JTextComponents
e978. Enumerating All the Views in a JTextComponent

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextArea    JTextField    JTextPane    Styles   


© 2002 Addison-Wesley.