Java Code Examples for javax.swing.JEditorPane#getDocument()

The following examples show how to use javax.swing.JEditorPane#getDocument() . 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 File: PHPActionTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void testInFile(String file, String actionName) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    runKitAction(ta, actionName, null);

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, goldenFileExtension());
}
 
Example 2
Source File: ViewUpdatesExtraFactoryTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCustomHighlightBeyondDocEnd() throws Exception {
    loggingOn();
    ViewUpdatesTesting.setTestValues(ViewUpdatesTesting.NO_OP_TEST_VALUE);
    JEditorPane pane = ViewUpdatesTesting.createPane();
    Document doc = pane.getDocument();
    final DocumentView docView = DocumentView.get(pane);
    final TestOffsetsHighlightsContainer highlights = new TestOffsetsHighlightsContainer();
    ViewUpdatesTesting.getSingleHighlightingLayerCustom(pane, highlights);
    highlights.setOffsetPairs(new int[] { 0, 5 });
    String text = "abcd\nefgh";
    doc.insertString(0, text, null);

    docView.op.viewsRebuildOrMarkInvalid(); // Manually mark affected children as invalid
    docView.ensureAllParagraphsChildrenAndLayoutValid();
    highlights.setOffsetPairs(new int[] { 3, 9 });
    doc.remove(0, doc.getLength());
}
 
Example 3
Source File: ToggleBlockCommentActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void testInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    Action a = new ToggleBlockCommentAction();
    a.actionPerformed(new ActionEvent(ta, 0, null));

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".toggleComment");
}
 
Example 4
Source File: ToggleBlockCommentActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void testInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    Action a = new ToggleBlockCommentAction();
    a.actionPerformed(new ActionEvent(ta, 0, null));

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".toggleComment");
}
 
Example 5
Source File: ViewHierarchyTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLongLineUndo() throws Exception {
    loggingOn();
    JEditorPane pane = ViewUpdatesTesting.createPane();
    Document doc = pane.getDocument();
    UndoManager undoManager = ViewUpdatesTesting.getUndoManager(doc);
    int lineLen = 4000;
    StringBuilder sb = new StringBuilder(lineLen + 10);
    for (int i = 0; i < lineLen; i++) {
        sb.append('a');
    }
    sb.append('\n');
    doc.insertString(0, sb.toString(), null);
    pane.modelToView(0);
    doc.remove(0, lineLen);
    pane.modelToView(0);
    undoManager.undo();
    undoManager.redo();
}
 
Example 6
Source File: JsCommentGeneratorEmbeddedTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception {
    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(null);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, preferences);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    // wait for generating comment
    Future<?> future = JsDocumentationCompleter.RP.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    future.get();

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);

    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
Example 7
Source File: CslTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void deleteChar(String original, String expected) throws Exception {
    String source = original;
    String reformatted = expected;
    Formatter formatter = getFormatter(null);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos+1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, null);

    runKitAction(ta, DefaultEditorKit.deletePrevCharAction, "\n");

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);
    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
Example 8
Source File: ViewHierarchyTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testEmptyCustomBounds() throws Exception {
    loggingOn();    
    JEditorPane pane = ViewUpdatesTesting.createPane();
    Document doc = pane.getDocument();
    pane.modelToView(0);
    doc.insertString(0, "hello\nworld\ngood\nmorning", null);
    Position startPos = doc.createPosition(3);
    pane.putClientProperty(DocumentView.START_POSITION_PROPERTY, startPos);
    pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, startPos);
    pane.modelToView(0); // Force rebuild of VH

    Position endPos = doc.createPosition(2);
    pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, endPos);
    pane.modelToView(0); // Force rebuild of VH
}
 
Example 9
Source File: GotoOppositeAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getApplicableFileObject(int[] caretPosHolder) {
    if (!EventQueue.isDispatchThread()) {
        // Unsafe to ask for an editor pane from a random thread.
        // E.g. org.netbeans.lib.uihandler.LogRecords.write asking for getName().
        Collection<? extends FileObject> dobs = Utilities.actionsGlobalContext().lookupAll(FileObject.class);
        return dobs.size() == 1 ? dobs.iterator().next() : null;
    }

    // TODO: Use the new editor library to compute this:
    // JTextComponent pane = EditorRegistry.lastFocusedComponent();

    TopComponent comp = TopComponent.getRegistry().getActivated();
    if(comp == null) {
        return null;
    }
    Node[] nodes = comp.getActivatedNodes();
    if (nodes != null && nodes.length == 1) {
        if (comp instanceof CloneableEditorSupport.Pane) { //OK. We have an editor
            EditorCookie ec = nodes[0].getLookup().lookup(EditorCookie.class);
            if (ec != null) {
                JEditorPane editorPane = NbDocument.findRecentEditorPane(ec);
                if (editorPane != null) {
                    if (editorPane.getCaret() != null) {
                            caretPosHolder[0] = editorPane.getCaret().getDot();
                    }
                    Document document = editorPane.getDocument();
                    return Source.create(document).getFileObject();
                }
            }
        } else {
            return UICommonUtils.getFileObjectFromNode(nodes[0]);
        }
    }
    
    return null;
}
 
Example 10
Source File: StyledEditorKit.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the document associated with an editor pane.
 *
 * @param e the editor
 * @return the document
 * @exception IllegalArgumentException for the wrong document type
 */
protected final StyledDocument getStyledDocument(JEditorPane e) {
    Document d = e.getDocument();
    if (d instanceof StyledDocument) {
        return (StyledDocument) d;
    }
    throw new IllegalArgumentException("document must be StyledDocument");
}
 
Example 11
Source File: ChatPrinter.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Method to get the current Document.
 *
 * @return the Chat document object.
 */
public Document getDocument() {
    if (JEditorPane != null)
        return JEditorPane.getDocument();
    else
        return null;
}
 
Example 12
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testNewlineInsertUndo() throws Exception {
    loggingOn();
    RandomTestContainer container = createContainer();
    JEditorPane pane = container.getInstance(JEditorPane.class);
    Document doc = pane.getDocument();
    doc.putProperty("mimeType", "text/plain");
    RandomTestContainer.Context context = container.context();
    DocumentTesting.insert(context, 0, "\n");
    DocumentTesting.remove(context, 0, 1);
    DocumentTesting.undo(context, 1);
}
 
Example 13
Source File: StyledEditorKit.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the document associated with an editor pane.
 *
 * @param e the editor
 * @return the document
 * @exception IllegalArgumentException for the wrong document type
 */
protected final StyledDocument getStyledDocument(JEditorPane e) {
    Document d = e.getDocument();
    if (d instanceof StyledDocument) {
        return (StyledDocument) d;
    }
    throw new IllegalArgumentException("document must be StyledDocument");
}
 
Example 14
Source File: MasterMatcherTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAreas() throws Exception {
    MockServices.setServices(MockMimeLookup.class);
    MockMimeLookup.setInstances(MimePath.EMPTY, new TestMatcher());
    
    AttributeSet EAS = SimpleAttributeSet.EMPTY;
    JEditorPane c = new JEditorPane();
    Document d = c.getDocument();
    OffsetsBag bag = new OffsetsBag(d);
    d.insertString(0, "text text { text } text", null);

    c.putClientProperty(MasterMatcher.PROP_MAX_BACKWARD_LOOKAHEAD, 256);
    c.putClientProperty(MasterMatcher.PROP_MAX_FORWARD_LOOKAHEAD, 256);
    
    TestMatcher.origin = new int [] { 2, 3 };
    TestMatcher.matches = new int [] { 10, 11 };
    
    MasterMatcher.get(c).highlight(d, 7, bag, EAS, EAS, EAS, EAS);
    TestMatcher.waitUntilCreated(1000);
    {
    TestMatcher tm = TestMatcher.lastMatcher;
    assertNotNull("No matcher created", tm);
    
    HighlightsSequence hs = bag.getHighlights(0, Integer.MAX_VALUE);
    assertTrue("Wrong number of highlighted areas", hs.moveNext());
    assertEquals("Wrong origin startOfset", 2, hs.getStartOffset());
    assertEquals("Wrong origin endOfset", 3, hs.getEndOffset());
    
    assertTrue("Wrong number of highlighted areas", hs.moveNext());
    assertEquals("Wrong match startOfset", 10, hs.getStartOffset());
    assertEquals("Wrong match endOfset", 11, hs.getEndOffset());
    }        
}
 
Example 15
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testInsertRemoveSingleChar() throws Exception {
    loggingOn();
    RandomTestContainer container = createContainer();
    JEditorPane pane = container.getInstance(JEditorPane.class);
    Document doc = pane.getDocument();
    doc.putProperty("mimeType", "text/plain");
    RandomTestContainer.Context context = container.context();
    ViewHierarchyRandomTesting.disableHighlighting(container);
    DocumentTesting.insert(context, 0, "a");
    DocumentTesting.remove(context, 0, 1);
    DocumentTesting.insert(context, 0, "b");
    DocumentTesting.undo(context, 1);
}
 
Example 16
Source File: BIEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public JComponent getToolbarRepresentation() {
    JComponent toolbar = null;
    JEditorPane jepane = getEditorPane();
    if (jepane != null) {
        Document doc = jepane.getDocument();
        if (doc instanceof NbDocument.CustomToolbar) {
            toolbar = ((NbDocument.CustomToolbar)doc).createToolbar(jepane);
        }
    }
    return toolbar;
}
 
Example 17
Source File: StyledEditorKit.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the document associated with an editor pane.
 *
 * @param e the editor
 * @return the document
 * @exception IllegalArgumentException for the wrong document type
 */
protected final StyledDocument getStyledDocument(JEditorPane e) {
    Document d = e.getDocument();
    if (d instanceof StyledDocument) {
        return (StyledDocument) d;
    }
    throw new IllegalArgumentException("document must be StyledDocument");
}
 
Example 18
Source File: DocumentTesting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get document from test container by consulting either an editor pane's document
 * or a document property.
 *
 * @param provider non-null property provider
 * @return document instance or null.
 */
public static Document getDocument(PropertyProvider provider) {
    JEditorPane pane = provider.getInstanceOrNull(JEditorPane.class);
    if (pane != null) {
        return pane.getDocument();
    } else {
        return provider.getInstanceOrNull(Document.class);
    }
}
 
Example 19
Source File: StyledEditorKit.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the document associated with an editor pane.
 *
 * @param e the editor
 * @return the document
 * @exception IllegalArgumentException for the wrong document type
 */
protected final StyledDocument getStyledDocument(JEditorPane e) {
    Document d = e.getDocument();
    if (d instanceof StyledDocument) {
        return (StyledDocument) d;
    }
    throw new IllegalArgumentException("document must be StyledDocument");
}
 
Example 20
Source File: ModelItem.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void updateFramesImpl(JEditorPane pane, boolean rawData) throws BadLocationException {
    Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    StyledDocument doc = (StyledDocument)pane.getDocument();
    Style timingStyle = doc.addStyle("timing", defaultStyle);
    StyleConstants.setForeground(timingStyle, Color.lightGray);
    Style infoStyle = doc.addStyle("comment", defaultStyle);
    StyleConstants.setForeground(infoStyle, Color.darkGray);
    StyleConstants.setBold(infoStyle, true);
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
    pane.setText("");
    StringBuilder sb = new StringBuilder();
    int lastFrameType = -1;
    for (Network.WebSocketFrame f : wsRequest.getFrames()) {
        int opcode = f.getOpcode();
        if (opcode == 0) { // "continuation frame"
            opcode = lastFrameType;
        } else {
            lastFrameType = opcode;
        }
        if (opcode == 1) { // "text frame"
            if (!rawData) {
                doc.insertString(doc.getLength(), formatter.format(f.getTimestamp()), timingStyle);
                doc.insertString(doc.getLength(), f.getDirection() == Network.Direction.SEND ? " SENT " : " RECV ", timingStyle);
            }
            doc.insertString(doc.getLength(), f.getPayload()+"\n", defaultStyle);
        } else if (opcode == 2) { // "binary frame"
            if (!rawData) {
                doc.insertString(doc.getLength(), formatter.format(f.getTimestamp()), timingStyle);
                doc.insertString(doc.getLength(), f.getDirection() == Network.Direction.SEND ? " SENT " : " RECV ", timingStyle);
            }
            // XXX: binary data???
            doc.insertString(doc.getLength(), f.getPayload()+"\n", defaultStyle);
        } else if (opcode == 8) { // "close frame"
            if (!rawData) {
                doc.insertString(doc.getLength(), formatter.format(f.getTimestamp()), timingStyle);
                doc.insertString(doc.getLength(), f.getDirection() == Network.Direction.SEND ? " SENT " : " RECV ", timingStyle);
            }
            doc.insertString(doc.getLength(), "Frame closed\n", infoStyle);
        }
    }
    data = sb.toString();
    pane.setCaretPosition(0);
}