Java Code Examples for javax.swing.text.Document#insertString()

The following examples show how to use javax.swing.text.Document#insertString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   File: CamelCaseOperations.java    License: Apache License 2.0 6 votes vote down vote up
static void replaceText(JTextComponent textComponent, final int offset, final int length, final String text) {
    if (!textComponent.isEditable()) {
        return;
    }
    final Document document = textComponent.getDocument();
    Runnable r = new Runnable() {
        public @Override void run() {
            try {
                if (length > 0) {
                    document.remove(offset, length);
                }
                document.insertString(offset, text, null);
            } catch (BadLocationException ble) {
                ErrorManager.getDefault().notify(ble);
            }
        }
    };
    if (document instanceof BaseDocument) {
        ((BaseDocument)document).runAtomic(r);
    } else {
        r.run();
    }
}
 
Example 2
Source Project: osp   File: MessageFrame.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void appletLog(final String msg, final Style style) {
  if((APPLET_MESSAGEFRAME==null)||!APPLET_MESSAGEFRAME.isDisplayable()) {
    createAppletMessageFrame();
  }
  Runnable refreshText = new Runnable() {
    public synchronized void run() {
      try {
        Document doc = APPLET_MESSAGEFRAME.textPane.getDocument();
        doc.insertString(doc.getLength(), msg+'\n', style);
        // scroll to display new message
        Rectangle rect = APPLET_MESSAGEFRAME.textPane.getBounds();
        rect.y = rect.height;
        APPLET_MESSAGEFRAME.textPane.scrollRectToVisible(rect);
      } catch(BadLocationException ex) {
        System.err.println(ex);
      }
    }

  };
  if(SwingUtilities.isEventDispatchThread()) {
    refreshText.run();
  } else {
    SwingUtilities.invokeLater(refreshText);
  }
}
 
Example 3
Source Project: netbeans   File: SyntaxHighlightingTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEvents() throws BadLocationException {
    final String text = "Hello !";
    Document doc = createDocument(TestTokenId.language(), text);
    assertTrue("TokenHierarchy should be active", TokenHierarchy.get(doc).isActive());

    SyntaxHighlighting layer = new SyntaxHighlighting(doc);
    L listener = new L();
    layer.addHighlightsChangeListener(listener);

    assertHighlights(
        text,
        TokenHierarchy.create(text, TestTokenId.language()).tokenSequence(),
        layer.getHighlights(Integer.MIN_VALUE, Integer.MAX_VALUE),
        ""
    );

    assertEquals("There should be no events", 0, listener.eventsCnt);

    final String addedText = "World";
    doc.insertString(6, addedText, SimpleAttributeSet.EMPTY);

    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertTrue("Wrong change start offset", 6 >= listener.lastStartOffset);
    assertTrue("Wrong change end offset", 6 + addedText.length() <= listener.lastEndOffset);
}
 
Example 4
Source Project: netbeans   File: TestCatalogModel.java    License: Apache License 2.0 6 votes vote down vote up
protected Document getDocument(FileObject fo){
    Document result = null;
    if (documentPooling) {
        result = documentPool().get(fo);
    }
    if (result != null) return result;
    try {

        File file = FileUtil.toFile(fo);
        FileInputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[fis.available()];
        result = new org.netbeans.editor.BaseDocument(true, fo.getMIMEType());
        result.remove(0, result.getLength());
        fis.read(buffer);
        fis.close();
        String str = new String(buffer);
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    if (documentPooling) {
        documentPool().put(fo, result);
    }
    return result;
}
 
Example 5
Source Project: netbeans   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static Document setDocumentContentTo(Document doc, InputStream in) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    StringBuffer sbuf = new StringBuffer();
    try {
        String line = null;
        while ((line = br.readLine()) != null) {
            sbuf.append(line);
            sbuf.append(System.getProperty("line.separator"));
        }
    } finally {
        br.close();
    }
    doc.remove(0, doc.getLength());
    doc.insertString(0,sbuf.toString(),null);
    return doc;
}
 
Example 6
Source Project: Spark   File: ChatRoom.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks to see if enter was pressed and validates room.
 *
 * @param e the KeyEvent
 */
private void checkForEnter(KeyEvent e) {
    final KeyStroke keyStroke = KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers());
    if (!keyStroke.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK)) &&
            e.getKeyChar() == KeyEvent.VK_ENTER) {
        e.consume();
        sendMessage();
        getChatInputEditor().setText("");
        getChatInputEditor().setCaretPosition(0);

        SparkManager.getWorkspace().getTranscriptPlugin().persistChatRoom(this);
    }
    else if (keyStroke.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK))) {
        final Document document = getChatInputEditor().getDocument();
        try {
            document.insertString(getChatInputEditor().getCaretPosition(), "\n", null);
            getChatInputEditor().requestFocusInWindow();
            chatAreaButton.getButton().setEnabled(true);
        }
        catch (BadLocationException badLoc) {
            Log.error("Error when checking for enter:", badLoc);
        }
    }
}
 
Example 7
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 6 votes vote down vote up
private void append(String str) {
  Document doc = jtp.getDocument();
  String text;
  if (doc.getLength() > LIMIT) {
    timerStop();
    startButton.setEnabled(false);
    text = "doc.getLength()>1000";
  } else {
    text = str;
  }
  try {
    doc.insertString(doc.getLength(), text + LS, null);
    jtp.setCaretPosition(doc.getLength());
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 8
public void testModifyTheFileAndThenPreventItToBeSavedOnClose() throws Exception {
    Document doc = support.openDocument();
    
    doc.insertString(0, "Ahoj", null);
    assertTrue("Modified", support.isModified());
    
    support.open();
    waitEQ();

    JEditorPane[] arr = getPanes();
    assertNotNull("There is one opened pane", arr);
    
    java.awt.Component c = arr[0];
    while (!(c instanceof CloneableEditor)) {
        c = c.getParent();
    }
    CloneableEditor ce = (CloneableEditor)c;

    toThrow = new IOException("NetworkConnectionLost");

    // say save at the end
    DD.toReturn = 0;
    boolean result = ce.close();
    assertFalse("Refused to save due to the exception", result);
    waitEQ();
    
    assertNotNull("There was a question", DD.options);
    
    String txt = doc.getText(0, doc.getLength());
    assertEquals("The right text is there", txt, "Ahoj");
    assertEquals("Nothing has been saved", "", content);
    
    arr = getPanes();
    assertNotNull("Panes are still open", arr);
}
 
Example 9
Source Project: netbeans   File: WordMatchTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testMultiDocs() throws Exception {
    JEditorPane pane = new JEditorPane();
    pane.setText("abc ax ec ajo");
    JFrame frame = new JFrame();
    frame.getContentPane().add(pane);
    frame.pack(); // Allows to EditorRegistry.register() to make an item in the component list
    EditorApiPackageAccessor.get().setIgnoredAncestorClass(JEditorPane.class);
    EditorApiPackageAccessor.get().register(pane);
    
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc a x ahoj", null);
    int docLen = doc.getLength();
    int offset = 5;
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "abc ", docLen + 2);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ahoj ", docLen + 3);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ax ", docLen + 1);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ajo ", docLen + 2);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ajo ", docLen + 2);
    pane.setText(""); // Ensure this doc would affect WordMatch for other docs
}
 
Example 10
Source Project: stendhal   File: KTextEdit.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Insert time stamp.
 *
 * @param header time stamp
 */
protected void insertTimestamp(final String header) {
	final Document doc = textPane.getDocument();
	try {
		if (header.length() > 0) {
			doc.insertString(doc.getLength(), header,
					textPane.getStyle("timestamp"));
		}
	} catch (final BadLocationException e) {
		logger.error("Couldn't insert initial text.", e);
	}
}
 
Example 11
public void testNullChildren() throws Exception {
    loggingOn();
    ViewUpdatesTesting.setTestValues(ViewUpdatesTesting.NO_OP_TEST_VALUE);
    JEditorPane pane = ViewUpdatesTesting.createPane();
    Document doc = pane.getDocument();
    final DocumentView docView = DocumentView.get(pane);
    // Insert twice the length of chars that would be otherwise serviced with local views creation
    int insertCount = ViewBuilder.MAX_CHARS_FOR_CREATE_LOCAL_VIEWS;
    String insertText = "a\n";
    for (int i = 0; i <= insertCount; i++) {
        doc.insertString(0, insertText, null);
    }
    int docLen = doc.getLength();
    int lineCount = doc.getDefaultRootElement().getElementCount();

    docView.op.releaseChildren(false);
    docView.ensureLayoutValidForInitedChildren();
    docView.children.ensureParagraphsChildrenAndLayoutValid(docView, 0, lineCount / 2, 0, 0);

    int hlStartOffset = docLen * 1 / 5;
    int hlStartPIndex = doc.getDefaultRootElement().getElementIndex(hlStartOffset);
    int hlEndOffset = hlStartOffset * 2;
    int hlEndPIndex = hlStartPIndex * 2;
    TestHighlightsViewFactory testFactory = ViewUpdatesTesting.getTestFactory(pane);
    List<TestHighlight> testHlts = ViewUpdatesTesting.getHighlightsCopy(testFactory);
    TestHighlight testHlt = TestHighlight.create(
            ViewUtils.createPosition(doc, hlStartOffset),
            ViewUtils.createPosition(doc, hlEndOffset),
            ViewUpdatesTesting.FONT_ATTRS[2]
    );
    testHlts.add(testHlt);
    testFactory.setHighlights(testHlts);
    testFactory.fireChange(hlStartOffset, hlEndOffset);
    docView.op.viewsRebuildOrMarkInvalid(); // Manually mark affected children as invalid

    docView.children.ensureParagraphsChildrenAndLayoutValid(docView,
            hlStartPIndex, hlEndPIndex, 0, 0);

    ViewUpdatesTesting.setTestValues();
}
 
Example 12
Source Project: netbeans   File: TestCatalogModel.java    License: Apache License 2.0 5 votes vote down vote up
private Document getDocument(FileObject fo){
    Document result = null;
    if (documentPooling) {
        result = documentPool().get(fo);
    }
    if (result != null) return result;
    try {
        
        File file = FileUtil.toFile(fo);
        FileInputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[fis.available()];
        result = new org.netbeans.editor.BaseDocument(
                org.netbeans.modules.xml.text.syntax.XMLKit.class, false);
        result.remove(0, result.getLength());
        fis.read(buffer);
        fis.close();
        String str = new String(buffer);
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    if (documentPooling) {
        documentPool().put(fo, result);
    }
    return result;
}
 
Example 13
protected int insert(String s, int start, int end, Document doc, boolean reformat)
        throws BadLocationException {
    try {
        doc.remove(start, end - start);
        doc.insertString(start, s, null);
    } catch (BadLocationException ble) {}
    
    if(reformat)
        reformat(doc, 0, doc.getLength());
    
    return start;
}
 
Example 14
public void testCheckOpenCompletion() throws BadLocationException {
    Document doc = createDocument();

    doc.insertString(0, "<", null);
    assertTrue(HtmlCompletionProvider.checkOpenCompletion(doc, 1, "<"));

    doc.insertString(1, "div", null);
    assertFalse(HtmlCompletionProvider.checkOpenCompletion(doc, 4, "div"));

    doc.insertString(4, " ", null);
    assertTrue(HtmlCompletionProvider.checkOpenCompletion(doc, 5, " "));

    doc.insertString(5, "/>", null);
    assertFalse(HtmlCompletionProvider.checkOpenCompletion(doc, 7, "/>"));

    doc.insertString(7, "</", null);
    assertTrue(HtmlCompletionProvider.checkOpenCompletion(doc, 9, "</"));

    doc.insertString(9, "div> &", null);
    assertTrue(HtmlCompletionProvider.checkOpenCompletion(doc, 15, "div> &"));

    //test end tag autocomplete
    doc.remove(0, doc.getLength());
    doc.insertString(0, "<div>", null);
    assertTrue(HtmlCompletionProvider.checkOpenCompletion(doc, 5, ">"));

}
 
Example 15
Source Project: netbeans   File: TextmateLexerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testNETBEANS2430() throws Exception {
    FileObject grammar = FileUtil.createData(FileUtil.getConfigRoot(), "Editors/text/test/grammar.json");
    try (OutputStream out = grammar.getOutputStream();
         Writer w = new OutputStreamWriter(out)) {
        w.write("{ \"scopeName\": \"test\", " +
                " \"patterns\": [\n" +
                "  { \"name\": \"string.test\",\n" +
                "    \"begin\": \"x([^x]+)x\",\n" +
                "    \"end\": \"x\\\\1x\"\n" +
                "   },\n" +
                "  { \"name\": \"whitespace.test\",\n" +
                "    \"match\": \" +\"\n" +
                "   }\n" +
                "]}\n");
    }
    grammar.setAttribute(LanguageHierarchyImpl.GRAMMAR_MARK, "test");
    Document doc = new PlainDocument();
    doc.insertString(0, " xaax xbbx\nxccx xaax ", null);
    doc.putProperty(Language.class, new LanguageHierarchyImpl("text/test", "test").language());
    TokenHierarchy hi = TokenHierarchy.get(doc);
    TokenSequence<?> ts = hi.tokenSequence();
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
    assertTokenProperties(ts, "test", "whitespace.test");
    //do not fully lex
    doc.insertString(3, "a", null);
    ts = hi.tokenSequence();
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
    assertTokenProperties(ts, "test", "whitespace.test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaaax");
    assertTokenProperties(ts, "test", "string.test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbx\n");
    assertTokenProperties(ts, "test", "string.test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xccx xaax \n");
    assertFalse(ts.moveNext());
}
 
Example 16
public void output(char c) {
    try {
        Document d = this.getDocument();
        d.insertString(d.getLength()-inputPos, ""+c, null);
        this.setCaretPosition(d.getLength()-inputPos);
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example 17
Source Project: netbeans   File: SnapshotTokenListTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testInputAttributes() throws Exception {
        Document d = new ModificationTextDocument();
        
        d.putProperty(Language.class,TestTokenId.language());
        
        d.insertString(0, "ident ident /** @see X */", null);
        
//        TokenHierarchy<?> h = TokenHierarchy.get(d).createSnapshot();
//        TokenSequence<?> ts = h.tokenSequence();
//        
//        LexerTestUtilities.assertNextTokenEquals(ts,TestTokenId.IDENTIFIER, "ident");
//        assertEquals(0, ts.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(ts,TestTokenId.WHITESPACE, " ");
//        assertEquals(5, ts.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(ts,TestTokenId.IDENTIFIER, "ident");
//        assertEquals(6, ts.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(ts,TestTokenId.WHITESPACE, " ");
//        assertEquals(11, ts.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(ts,TestTokenId.JAVADOC_COMMENT, "/** @see X */");
//        assertEquals(12, ts.offset());
//        
//        TokenSequence<?> inner = ts.embedded();
//        
//        assertNotNull(inner);
//        
//        LexerTestUtilities.assertNextTokenEquals(inner,TestJavadocTokenId.OTHER_TEXT, " ");
//        assertEquals(15, inner.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(inner,TestJavadocTokenId.TAG, "@see");
//        assertEquals(16, inner.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(inner,TestJavadocTokenId.OTHER_TEXT, " ");
//        assertEquals(20, inner.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(inner,TestJavadocTokenId.IDENT, "X");
//        assertEquals(21, inner.offset());
//        
//        LexerTestUtilities.assertNextTokenEquals(inner,TestJavadocTokenId.OTHER_TEXT, " ");
//        assertEquals(22, inner.offset());
    }
 
Example 18
/**
 * Insert the given String into the textcomponent.  If the string contains
 * the | vertical BAr char, then it will not be inserted, and the cursor will
 * be set to its location.
 * If there are TWO vertical bars, then the text between them will be selected
 * If the toInsert String is multiLine, then indentation of all following lines
 * will be the same as the first line.  TAB characters will be replaced by
 * the number of spaces in the document's TAB property.
 * @param target
 * @param dot
 * @param toInsert
 * @throws javax.swing.text.BadLocationException
 */
public static void insertMagicString(JTextComponent target, int dot, String toInsert)
	throws BadLocationException {
	Document doc = target.getDocument();
	String[] lines = toInsert.split("\n");
	if (lines.length > 1) {
		// multi line strings will need to be indented
		String tabToSpaces = getTab(target);
		String currentLine = getLineAt(target, dot);
		String currentIndent = getIndent(currentLine);
		StringBuilder sb = new StringBuilder(toInsert.length());
		boolean firstLine = true;
		for (String l : lines) {
			if (!firstLine) {
				sb.append(currentIndent);
			}
			firstLine = false;
			// replace tabs with spaces.
			sb.append(l.replace("\t", tabToSpaces));
			sb.append("\n");
		}
		toInsert = sb.toString();
	}
	if (toInsert.indexOf('|') >= 0) {
		int ofst = toInsert.indexOf('|');
		int ofst2 = toInsert.indexOf('|', ofst + 1);
		toInsert = toInsert.replace("|", "");
		doc.insertString(dot, toInsert, null);
		dot = target.getCaretPosition();
		int strLength = toInsert.length();
		if (ofst2 > 0) {
			// note that we already removed the first |, so end offset is now
			// one less than what it was.
			target.select(dot + ofst - strLength, dot + ofst2 - strLength - 1);
		} else {
			target.setCaretPosition(dot + ofst - strLength);
		}
	} else {
		doc.insertString(dot, toInsert, null);
	}
}
 
Example 19
Source Project: netbeans   File: JavaTokenListTest.java    License: Apache License 2.0 4 votes vote down vote up
private void tokenListTest(String documentContent, String... golden) throws Exception {
    Document doc = new PlainDocument();
    
    doc.putProperty(Language.class, JavaTokenId.language());
    
    doc.insertString(0, documentContent, null);
    
    List<String> words = new ArrayList<String>();
    TokenList l = new JavaTokenList(doc);
    
    l.setStartOffset(0);
    
    while (l.nextWord()) {
        words.add(l.getCurrentWordText().toString());
    }
    
    assertEquals(Arrays.asList(golden), words);
}
 
Example 20
Source Project: netbeans   File: JavaTokenListTest.java    License: Apache License 2.0 4 votes vote down vote up
private void tokenListTestWithWriting(String documentContent, int offset, String text, int startOffset, String... golden) throws Exception {
    Document doc = new PlainDocument();
    
    doc.putProperty(Language.class, JavaTokenId.language());
    
    doc.insertString(0, documentContent, null);
    
    List<String> words = new ArrayList<String>();
    TokenList l = new JavaTokenList(doc);
    
    while (l.nextWord()) {
    }

    doc.insertString(offset, text, null);
    
    l.setStartOffset(startOffset);
    
    while (l.nextWord()) {
        words.add(l.getCurrentWordText().toString());
    }

    assertEquals(Arrays.asList(golden), words);
}