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

The following examples show how to use javax.swing.JEditorPane#setDocument() . 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: JspCompletionQueryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void testCompletionResults(String testFile) throws IOException, BadLocationException {
    FileObject source = getTestFile(DATA_DIR_BASE + testFile);
    BaseDocument doc = getDocument(source);
    JspCompletionQuery query = JspCompletionQuery.instance();
    JEditorPane component = new JEditorPane();
    component.setDocument(doc);

    StringBuffer output = new StringBuffer();
    for (int i = 0; i < doc.getLength(); i++) {
        JspCompletionQuery.CompletionResultSet result = new JspCompletionQuery.CompletionResultSet();
        
        query.query(result, component, i);
        if (result != null) {
            List<CompletionItem> items = result.getItems();
            output.append(i + ":");
            output.append('[');
            Iterator<CompletionItem> itr = items.iterator();
            while (itr.hasNext()) {
                CompletionItem ci = itr.next();
                if (ci instanceof JspCompletionItem) {
                    //test only html completion items
                    JspCompletionItem htmlci = (JspCompletionItem) ci;
                    output.append(htmlci.getItemText());
                    if (itr.hasNext()) {
                        output.append(',');
                    }
                }
            }
            output.append(']');
            output.append('\n');
        }
    }

    assertDescriptionMatches(source, output.toString(), false, ".pass", true);

}
 
Example 2
Source File: FoldView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public JComponent getToolTip(double x, double y, Shape allocation) {
    Container container = getContainer();
    if (container instanceof JEditorPane) {
        JEditorPane editorPane = (JEditorPane) getContainer();
        JEditorPane tooltipPane = new JEditorPane();
        EditorKit kit = editorPane.getEditorKit();
        Document doc = getDocument();
        if (kit != null && doc != null) {
            Element lineRootElement = doc.getDefaultRootElement();
            tooltipPane.putClientProperty(FoldViewFactory.DISPLAY_ALL_FOLDS_EXPANDED_PROPERTY, true);
            try {
                // Start-offset of the fold => line start => position
                int lineIndex = lineRootElement.getElementIndex(fold.getStartOffset());
                Position pos = doc.createPosition(
                        lineRootElement.getElement(lineIndex).getStartOffset());
                // DocumentView.START_POSITION_PROPERTY
                tooltipPane.putClientProperty("document-view-start-position", pos); // NOI18N
                // End-offset of the fold => line end => position
                lineIndex = lineRootElement.getElementIndex(fold.getEndOffset());
                pos = doc.createPosition(lineRootElement.getElement(lineIndex).getEndOffset());
                // DocumentView.END_POSITION_PROPERTY
                tooltipPane.putClientProperty("document-view-end-position", pos); // NOI18N
                tooltipPane.putClientProperty("document-view-accurate-span", true); // NOI18N
                // Set the same kit and document
                tooltipPane.setEditorKit(kit);
                tooltipPane.setDocument(doc);
                tooltipPane.setEditable(false);
                return new FoldToolTip(editorPane, tooltipPane, getBorderColor());
            } catch (BadLocationException e) {
                // => return null
            }
        }
    }
    return null;
}
 
Example 3
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testToolTipView() throws Exception {
        loggingOn();
        RandomTestContainer container = createContainer();
        final JEditorPane pane = container.getInstance(JEditorPane.class);
        final Document doc = pane.getDocument();
        doc.putProperty("mimeType", "text/plain");
        RandomTestContainer.Context context = container.context();
//        ViewHierarchyRandomTesting.disableHighlighting(container);
        DocumentTesting.setSameThreadInvoke(context, true); // Do not post to EDT
        DocumentTesting.insert(context, 0, "abc\ndef\nghi\n");
        final JEditorPane[] toolTipPaneRef = new JEditorPane[1];
        final BadLocationException[] excRef = new BadLocationException[1];
        final JFrame[] toolTipFrameRef = new JFrame[1];
        Runnable tooltipRun = new Runnable() {
            @Override
            public void run() {
                JEditorPane toolTipPane = new JEditorPane();
                toolTipPaneRef[0] = toolTipPane;
                toolTipPane.setEditorKit(pane.getEditorKit());
                try {
                    Position startPos = doc.createPosition(4); // Line begining
                    Position endPos = doc.createPosition(8); // Line boundary too
                    toolTipPane.putClientProperty("document-view-start-position", startPos);
                    toolTipPane.putClientProperty("document-view-end-position", endPos);
                    toolTipPane.setDocument(doc);
                    JFrame toolTipFrame = new JFrame("ToolTip Frame");
                    toolTipFrameRef[0] = toolTipFrame;
                    toolTipFrame.getContentPane().add(new JScrollPane(toolTipPane));
                    toolTipFrame.setSize(100, 100);
                    toolTipFrame.setVisible(true);

                    doc.insertString(4, "o", null);
                    toolTipPane.setFont(new Font("Monospaced", Font.PLAIN, 22)); // Force VH rebuild
                    toolTipPane.modelToView(6);
                    doc.remove(3, 3);
                    doc.insertString(4, "ab", null);
                    
                    assert (endPos.getOffset() == 8);
                    doc.remove(7, 2);
                    toolTipPane.setFont(new Font("Monospaced", Font.PLAIN, 23)); // Force VH rebuild
                    toolTipPane.modelToView(6);

                } catch (BadLocationException ex) {
                    excRef[0] = ex;
                }

            }
        };
        SwingUtilities.invokeAndWait(tooltipRun);
        if (excRef[0] != null) {
            throw new IllegalStateException(excRef[0]);
        }

        DocumentTesting.setSameThreadInvoke(context, false);
        DocumentTesting.undo(context, 2);
        DocumentTesting.undo(context, 1);
        DocumentTesting.undo(context, 1);
        DocumentTesting.redo(context, 4);
        
        // Hide tooltip's frame
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (toolTipFrameRef[0] != null) {
                    toolTipFrameRef[0].setVisible(false);
                }
            }
        });
    }
 
Example 4
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRandomModsPlainText() throws Exception {
        loggingOn();
        RandomTestContainer container = createContainer();
        final JEditorPane pane = container.getInstance(JEditorPane.class);
        final Document doc = pane.getDocument();
        doc.putProperty("mimeType", "text/plain");
        ViewHierarchyRandomTesting.initRandomText(container);
        ViewHierarchyRandomTesting.addRound(container).setOpCount(OP_COUNT);
        ViewHierarchyRandomTesting.testFixedScenarios(container);
        container.run(1271950385168L); // Failed at op=750
//        container.run(1270806278503L);
//        container.run(1270806786819L);
//        container.run(1270806387223L);
//        container.run(1271372510390L);

//        RandomTestContainer.Context context = container.context();
//        DocumentTesting.undo(context, 2);
//        DocumentTesting.redo(context, 2);
        // Simulate tooltip pane
        final JEditorPane[] toolTipPaneRef = new JEditorPane[1];
        final BadLocationException[] excRef = new BadLocationException[1];
        final JFrame[] toolTipFrameRef = new JFrame[1];
        Runnable tooltipRun = new Runnable() {
            @Override
            public void run() {
                JEditorPane toolTipPane = new JEditorPane();
                toolTipPaneRef[0] = toolTipPane;
                toolTipPane.setEditorKit(pane.getEditorKit());
                try {
                    toolTipPane.putClientProperty("document-view-start-position", doc.createPosition(4));
                    toolTipPane.putClientProperty("document-view-end-position", doc.createPosition(20));
                } catch (BadLocationException ex) {
                    excRef[0] = ex;
                }
                toolTipPane.setDocument(doc);
                JFrame toolTipFrame = new JFrame("ToolTip Frame");
                toolTipFrameRef[0] = toolTipFrame;
                toolTipFrame.getContentPane().add(new JScrollPane(toolTipPane));
                toolTipFrame.setSize(100, 100);
                toolTipFrame.setVisible(true);
            }
        };
        SwingUtilities.invokeAndWait(tooltipRun);
        if (excRef[0] != null) {
            throw new IllegalStateException(excRef[0]);
        }

        container.run(0L); // Test random ops
        // Exclude caret row highlighting
        excludeHighlights(pane);
        container.run(0L); // Re-run test

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (toolTipFrameRef[0] != null) {
                    toolTipFrameRef[0].setVisible(false);
                }
            }
        });
    }
 
Example 5
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRandomModsJava() throws Exception {
    RandomTestContainer container = createContainer();
    final JEditorPane pane = container.getInstance(JEditorPane.class);
    final Document doc = pane.getDocument();
    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");
    ViewHierarchyRandomTesting.initRandomText(container);
    ViewHierarchyRandomTesting.addRound(container).setOpCount(OP_COUNT);
    loggingOn();
    container.setLogOp(true);
    DocumentTesting.setLogDoc(container, true);
    ViewHierarchyRandomTesting.testFixedScenarios(container);
    assert (Logger.getLogger("org.netbeans.editor.view.check").isLoggable(Level.FINEST));
    Logger.getLogger("org.netbeans.editor.view.build").setLevel(Level.FINE);
    container.runInit(1271946202898L);
    container.runOps(0);
    
    // Simulate tooltip pane
    final JEditorPane[] toolTipPaneRef = new JEditorPane[1];
    final BadLocationException[] excRef = new BadLocationException[1];
    final JFrame[] toolTipFrameRef = new JFrame[1];
    Runnable tooltipRun = new Runnable() {
        @Override
        public void run() {
            JEditorPane toolTipPane = new JEditorPane();
            toolTipPaneRef[0] = toolTipPane;
            toolTipPane.setEditorKit(pane.getEditorKit());
            try {
                toolTipPane.putClientProperty("document-view-start-position", doc.createPosition(4));
                toolTipPane.putClientProperty("document-view-end-position", doc.createPosition(20));
            } catch (BadLocationException ex) {
                excRef[0] = ex;
            }
            toolTipPane.setDocument(doc);
            JFrame toolTipFrame = new JFrame("ToolTip Frame");
            toolTipFrameRef[0] = toolTipFrame;
            toolTipFrame.getContentPane().add(new JScrollPane(toolTipPane));
            toolTipFrame.setSize(100, 100);
            toolTipFrame.setVisible(true);
        }
    };
    SwingUtilities.invokeAndWait(tooltipRun);
    if (excRef[0] != null) {
        throw new IllegalStateException(excRef[0]);
    }

    
    container.run(1290550667174L);
    container.run(0L); // Test random ops
    // Exclude caret row highlighting
    excludeHighlights(pane);
    container.run(0L); // Re-run test

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            if (toolTipFrameRef[0] != null) {
                toolTipFrameRef[0].setVisible(false);
            }
        }
    });
}
 
Example 6
Source File: CompletionTestBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void performTest(String source, int caretPos, String textToInsert, String toPerformItemRE, String goldenFileName, String sourceLevel) throws Exception {
    this.sourceLevel.set(sourceLevel);
    File testSource = new File(getWorkDir(), "test/Test.java");
    testSource.getParentFile().mkdirs();
    copyToWorkDir(new File(getDataDir(), "org/netbeans/modules/java/editor/completion/data/" + source + ".java"), testSource);
    FileObject testSourceFO = FileUtil.toFileObject(testSource);
    assertNotNull(testSourceFO);
    DataObject testSourceDO = DataObject.find(testSourceFO);
    assertNotNull(testSourceDO);
    EditorCookie ec = (EditorCookie) testSourceDO.getCookie(EditorCookie.class);
    assertNotNull(ec);
    final Document doc = ec.openDocument();
    assertNotNull(doc);
    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");
    int textToInsertLength = textToInsert != null ? textToInsert.length() : 0;
    if (textToInsertLength > 0)
        doc.insertString(caretPos, textToInsert, null);
    Source s = Source.create(doc);
    List<? extends CompletionItem> items = JavaCompletionProvider.query(s, CompletionProvider.COMPLETION_QUERY_TYPE, caretPos + textToInsertLength, caretPos + textToInsertLength);
    Collections.sort(items, CompletionItemComparator.BY_PRIORITY);
    
    assertNotNull(goldenFileName);            

    Pattern p = Pattern.compile(toPerformItemRE);
    CompletionItem item = null;            
    for (CompletionItem i : items) {
        if (p.matcher(i.toString()).find()) {
            item = i;
            break;
        }
    }            
    assertNotNull(item);

    JEditorPane editor = new JEditorPane();
    SwingUtilities.invokeAndWait(() -> {
        editor.setEditorKit(new JavaKit());
    });
    editor.setDocument(doc);
    editor.setCaretPosition(caretPos + textToInsertLength);
    item.defaultAction(editor);

    SwingUtilities.invokeAndWait(() -> {});

    File output = new File(getWorkDir(), getName() + ".out2");
    Writer out = new FileWriter(output);            
    out.write(doc.getText(0, doc.getLength()));
    out.close();

    File goldenFile = getGoldenFile(goldenFileName);
    File diffFile = new File(getWorkDir(), getName() + ".diff");

    assertFile(output, goldenFile, diffFile, new WhitespaceIgnoringDiff());
    
    LifecycleManager.getDefault().saveAll();
}
 
Example 7
Source File: EditorPaneDemo.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public EditorPaneDemo(Language language, boolean maintainLookbacks,
String initialContent) {

    super(new PlainDocument(), language, maintainLookbacks);
    
    JFrame frame = new JFrame();
    frame.addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            System.exit(0);
        }
    });

    frame.setTitle("Test of " + splitClassName(language.getClass().getName())[1]
        + " - Use Ctrl+L to dump tokens");

    JEditorPane jep = new JEditorPane();
    
    Document doc = getDocument();
    jep.setDocument(doc);
    // Insert initial content string
    try {
        if (initialContent != null) {
            doc.insertString(0, initialContent, null);
        }
    } catch (BadLocationException e) {
        e.printStackTrace();
        return;
    }
    
    // Initially debug token changes
    setDebugTokenChanges(true);

    frame.getContentPane().add(jep);
    
    DumpAction da = new DumpAction();
    jep.registerKeyboardAction(da,
        KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK), 0);
    
    DebugTokenChangesAction dtca = new DebugTokenChangesAction();
    jep.registerKeyboardAction(dtca,
        KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK), 0);
    
    
    System.err.println("NOTE: Press Ctrl+L to dump the document's token list.\n");
    System.err.println("      Press Ctrl+T to toggle debugging of token changes.\n");
    
    // Debug initially
    dump();

    frame.setSize(400, 300);
    frame.setVisible(true);
    
}
 
Example 8
Source File: TutorialBrowser.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
private Component createContentPanel() {
	contentGbc = new GridBagConstraints();

	contentPanel = new JPanel(new GridBagLayout()) {

		@Override
		public Dimension getPreferredSize() {
			return new Dimension(getParent().getWidth(), super.getPreferredSize().height);
		}
	};
	contentPanel.setBackground(Colors.WHITE);

	jEditorPane = new JEditorPane() {

		@Override
		public Dimension getPreferredSize() {
			return new Dimension(getParent().getWidth(), super.getPreferredSize().height);
		}
	};
	jEditorPane.setEditable(false);
	contentGbc.gridx = 0;
	contentGbc.gridy = 0;
	contentGbc.weightx = 1.0f;
	contentGbc.fill = GridBagConstraints.HORIZONTAL;
	contentPanel.add(jEditorPane, contentGbc);

	// add filler at bottom
	contentGbc.gridy += 1;
	contentGbc.weighty = 1.0f;
	contentGbc.fill = GridBagConstraints.BOTH;
	contentPanel.add(new JLabel(), contentGbc);

	// prepare contentGbc for feedback form
	contentGbc.gridy += 1;
	contentGbc.weighty = 0.0f;
	contentGbc.fill = GridBagConstraints.HORIZONTAL;

	scrollPane = new ExtendedJScrollPane(contentPanel);
	scrollPane.setBorder(null);

	HTMLEditorKit kit = new HTMLEditorKit();
	jEditorPane.setEditorKit(kit);
	jEditorPane.setMargin(new Insets(0, 0, 0, 0));

	Document doc = kit.createDefaultDocument();
	jEditorPane.setDocument(doc);
	jEditorPane.setText(String.format(INFO_TEMPLATE, NO_TUTORIAL_SELECTED));
	jEditorPane.addHyperlinkListener(e -> {

		if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			ActionStatisticsCollector.INSTANCE.log(ActionStatisticsCollector.TYPE_GETTING_STARTED,
					TUTORIAL_BROWSER_DOCK_KEY, "open_remote_url");
			RMUrlHandler.handleUrl(e.getURL().toString());
		}
	});
	return scrollPane;
}
 
Example 9
Source File: ArtARDemo.java    From COMP3204 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public JPanel getComponent(int width, int height) throws IOException {
	final JPanel container = new JPanel();
	container.setSize(width, height);
	container.setPreferredSize(container.getSize());

	final OverlayLayout overlay = new OverlayLayout(container);
	container.setLayout(overlay);

	labelField = new JEditorPane();
	labelField.setOpaque(false);
	labelField.setSize(640 - 50, 480 - 50);
	labelField.setPreferredSize(labelField.getSize());
	labelField.setMaximumSize(labelField.getSize());
	labelField.setContentType("text/html");

	// add a HTMLEditorKit to the editor pane
	final HTMLEditorKit kit = new HTMLEditorKit();
	labelField.setEditorKit(kit);

	final StyleSheet styleSheet = kit.getStyleSheet();
	styleSheet.addRule("body {color:#FF00FF; font-family:courier;}");
	styleSheet.addRule("h1 {font-size: 60pt}");
	styleSheet.addRule("h2 {font-size: 50pt }");

	final Document doc = kit.createDefaultDocument();
	labelField.setDocument(doc);

	// final GridBagConstraints gbc = new GridBagConstraints();
	// gbc.gridy = 1;
	// panel.add(labelField, gbc);
	container.add(labelField);
	// labelField.setAlignmentX(0.5f);
	// labelField.setAlignmentY(0.5f);

	final JPanel panel = super.getComponent(width, height);
	container.add(panel);

	vc.getDisplay().addVideoListener(this);

	isRunning = true;
	new Thread(this).start();

	return container;
}
 
Example 10
Source File: CheckForUpdateAction.java    From nextreports-designer with Apache License 2.0 4 votes vote down vote up
private JComponent createPanel(String html) {
	System.setProperty("awt.useSystemAAFontSettings", "on");
	final JEditorPane editorPane = new JEditorPane();    	
	HTMLEditorKit kit = new HTMLEditorKit();
	editorPane.setEditorKit(kit);
    editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
    editorPane.setFont(new Font("Arial", Font.PLAIN, 12));
    editorPane.setPreferredSize(new Dimension(350, 120));
    editorPane.setEditable(false);
    editorPane.setContentType("text/html");
    editorPane.setBackground(new Color(234, 241, 248));        
   
    Document doc = kit.createDefaultDocument();
    editorPane.setDocument(doc);
    editorPane.setText(html);

    // Add Hyperlink listener to process hyperlinks
    editorPane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(final HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        SwingUtilities.getWindowAncestor(editorPane).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        editorPane.setToolTipText(e.getURL().toExternalForm());
                    }
                });
            } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
                EventQueue.invokeLater(new Runnable() {
                    public void run() {                            
                        SwingUtilities.getWindowAncestor(editorPane).setCursor(Cursor.getDefaultCursor());
                        editorPane.setToolTipText(null);
                    }
                });
            } else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {       
            	    FileUtil.openUrl(e.getURL().toString(), AboutAction.class);                       
            }
        }
    });        
    editorPane.addMouseListener(mouseListener);
    JScrollPane sp = new JScrollPane(editorPane);       
    return sp;
}
 
Example 11
Source File: ChatPrinter.java    From Spark with Apache License 2.0 4 votes vote down vote up
private void setDocument(String type, Document document) {
    setContentType(type);
    JEditorPane.setDocument(document);
}