Java Code Examples for javax.swing.JEditorPane

The following examples show how to use javax.swing.JEditorPane. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   Source File: CompletionTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**Currently, this method is supposed to be runned inside the AWT thread.
 * If this condition is not fullfilled, an IllegalStateException is
 * thrown. Do NOT modify this behaviour, or deadlock (or even Swing
 * or NetBeans winsys data corruption) may occur.
 *
 * Currently threading model of this method is compatible with
 * editor code completion threading model. Revise if this changes
 * in future.
 */
private void testPerform(PrintWriter out, PrintWriter log,
        JEditorPane editor,
        boolean unsorted,
        String assign,
        int lineIndex,
        int queryType) throws BadLocationException, IOException {
    if (!SwingUtilities.isEventDispatchThread())
        throw new IllegalStateException("The testPerform method may be called only inside AWT event dispatch thread.");
    
    BaseDocument doc        = Utilities.getDocument(editor);
    int          lineOffset = Utilities.getRowStartFromLineOffset(doc, lineIndex -1);
    
    editor.grabFocus();
    editor.getCaret().setDot(lineOffset);
    doc.insertString(lineOffset, assign, null);
    reparseDocument((DataObject) doc.getProperty(doc.StreamDescriptionProperty));
    completionQuery(out, log, editor, unsorted, queryType);
}
 
Example 2
Source Project: JDKSourceCode1.8   Source File: StyledEditorKit.java    License: MIT License 6 votes vote down vote up
/**
 * Sets the font size.
 *
 * @param e the action event
 */
public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
        int size = this.size;
        if ((e != null) && (e.getSource() == editor)) {
            String s = e.getActionCommand();
            try {
                size = Integer.parseInt(s, 10);
            } catch (NumberFormatException nfe) {
            }
        }
        if (size != 0) {
            MutableAttributeSet attr = new SimpleAttributeSet();
            StyleConstants.setFontSize(attr, size);
            setCharacterAttributes(editor, attr, false);
        } else {
            UIManager.getLookAndFeel().provideErrorFeedback(editor);
        }
    }
}
 
Example 3
Source Project: littleluck   Source File: HTMLPanel.java    License: Apache License 2.0 6 votes vote down vote up
public void hyperlinkUpdate(HyperlinkEvent event) {
    JEditorPane descriptionPane = (JEditorPane) event.getSource();
    HyperlinkEvent.EventType type = event.getEventType();
    if (type == HyperlinkEvent.EventType.ACTIVATED) {
        try {
            DemoUtilities.browse(event.getURL().toURI());
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e);
        }

    } else if (type == HyperlinkEvent.EventType.ENTERED) {
        defaultCursor = descriptionPane.getCursor();
        descriptionPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    } else if (type == HyperlinkEvent.EventType.EXITED) {
        descriptionPane.setCursor(defaultCursor);
    }
}
 
Example 4
Source Project: netbeans   Source File: DrawEngineTest.java    License: Apache License 2.0 6 votes vote down vote up
@RandomlyFails
public void testModelToViewCorrectness() throws Throwable {
    for(String text : TEXTS) {
        JEditorPane jep = createJep(text);
        try {
            checkModelToViewCorrectness(jep);
        } catch (Throwable e) {
            System.err.println("testModelToViewCorrectness processing {");
            System.err.println(text);
            System.err.println("} failed with:");
            e.printStackTrace();
            throw e;
        } finally {
            JFrame frame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, jep);
            if (frame != null) {
                frame.dispose();
            }
        }
    }
}
 
Example 5
Source Project: ramus   Source File: ScriptEditor.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public JComponent createComponent() {
    JScrollPane pane = new JScrollPane();
    editorPane = new JEditorPane();
    pane.setViewportView(editorPane);
    if (scriptPath.endsWith(".js"))
        editorPane.setContentType("text/javascript");
    byte[] bs = framework.getEngine().getStream(scriptPath);
    if (bs == null)
        bs = new byte[]{};
    try {
        editorPane.setText(new String(bs, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (!saveScriptAction.isEnabled())
        editorPane.setEditable(false);
    return pane;
}
 
Example 6
Source Project: netbeans   Source File: ResourceSupport.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isExcludedProperty1(FormProperty prop) {
    if (!Boolean.TRUE.equals(prop.getValue(EXCLUSION_DETERMINED))) {
        prop.setValue(EXCLUSION_DETERMINED, true);
        Object propOwner = prop.getPropertyContext().getOwner();
        Class type = null;
        if (propOwner instanceof RADComponent) {
            type = ((RADComponent)propOwner).getBeanClass();
        } else if (propOwner instanceof FormProperty) {
            type = ((FormProperty)propOwner).getValueType();
        }
        String propName = prop.getName();
        boolean excl = (Component.class.isAssignableFrom(type) && "name".equals(propName)) // NOI18N
                || (JEditorPane.class.isAssignableFrom(type) && "contentType".equals(propName)); // NOI18N
        prop.setValue(EXCLUDE_FROM_RESOURCING, excl);
        return excl;
    }
    return false;
}
 
Example 7
Source Project: Java8CN   Source File: StyledEditorKit.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the font family.
 *
 * @param e the event
 */
public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
        String family = this.family;
        if ((e != null) && (e.getSource() == editor)) {
            String s = e.getActionCommand();
            if (s != null) {
                family = s;
            }
        }
        if (family != null) {
            MutableAttributeSet attr = new SimpleAttributeSet();
            StyleConstants.setFontFamily(attr, family);
            setCharacterAttributes(editor, attr, false);
        } else {
            UIManager.getLookAndFeel().provideErrorFeedback(editor);
        }
    }
}
 
Example 8
Source Project: netbeans   Source File: EditorContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns identifier currently selected in editor or <code>null</code>.
 *
 * @return identifier currently selected in editor or <code>null</code>
 */
@Override
public String getSelectedIdentifier () {
    JEditorPane ep = contextDispatcher.getCurrentEditor ();
    if (ep == null) {
        return null;
    }
    Caret caret = ep.getCaret();
    if (caret == null) {
        // No caret => no selected text
        return null;
    }
    String s = ep.getSelectedText ();
    if (s == null) {
        return null;
    }
    if (Utilities.isJavaIdentifier (s)) {
        return s;
    }
    return null;
}
 
Example 9
Source Project: netbeans   Source File: HintsPanelLogic.java    License: Apache License 2.0 6 votes vote down vote up
void connect( JTree errorTree, JComboBox severityComboBox, 
              JCheckBox tasklistCheckBox, JPanel customizerPanel,
              JEditorPane descriptionTextArea) {
    
    this.errorTree = errorTree;
    this.severityComboBox = severityComboBox;
    this.tasklistCheckBox = tasklistCheckBox;
    this.customizerPanel = customizerPanel;
    this.descriptionTextArea = descriptionTextArea;        
    
    valueChanged( null );
    
    errorTree.addKeyListener(this);
    errorTree.addMouseListener(this);
    errorTree.getSelectionModel().addTreeSelectionListener(this);
        
    severityComboBox.addActionListener(this);
    tasklistCheckBox.addChangeListener(this);
    
}
 
Example 10
Source Project: dragonwell8_jdk   Source File: bug7189299.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void setup() {
    /**
     * Note the input type is not restricted to "submit". Types "image",
     * "checkbox", "radio" have the same problem.
     */
    html = new JEditorPane("text/html",
            "<html><body><form action=\"http://localhost.cgi\">"
                    + "<input type=submit name=submit value=\"submit\"/>"
                    + "</form></body></html>");
    frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.add(html, BorderLayout.CENTER);
    frame.setSize(200, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
 
Example 11
Source Project: netbeans   Source File: RenameWithTimestampChangeTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testRenameTheDocumentWhilechangingTheTimestamp() throws Exception {
    Document doc = edit.openDocument();
    
    assertFalse("Not Modified", edit.isModified());

    doc.insertString(0, "Base change\n", null);
    assertTrue("Is Modified", edit.isModified());
    
    edit.open();
    waitEQ();

    JEditorPane[] arr = getPanes();
    assertNotNull("There is one opened pane", arr);
    
    obj.getFolder().rename("newName");

    assertEquals("Last modified incremented by 10000", lastM + 10000, obj.getPrimaryFile().lastModified().getTime());
    assertTrue("Name contains newName: " + obj.getPrimaryFile(), obj.getPrimaryFile().getPath().contains("newName/"));
    
    waitEQ();
    edit.saveDocument();
    
    if (DD.error != null) {
        fail("Error in dialog:\n" + DD.error);
    }
}
 
Example 12
Source Project: minifierbeans   Source File: JSONMinifyClipboard.java    License: Apache License 2.0 6 votes vote down vote up
protected final void jsonMinify(final Node[] activatedNodes) {
    final EditorCookie editorCookie
            = Utilities.actionsGlobalContext().lookup(EditorCookie.class);

    for (final JEditorPane pane : editorCookie.getOpenedPanes()) {
        if (pane.isShowing()
                && pane.getSelectionEnd() > pane.getSelectionStart()) {
            try {
                StringSelection content = new StringSelection(selectedSourceAsMinify(pane));
                Toolkit.getDefaultToolkit().getSystemClipboard().
                        setContents(content, content);
                return;
            } catch (final HeadlessException e) {
                org.openide.ErrorManager.getDefault().notify(e);
            }
        }
    }
}
 
Example 13
/**
 * Sets the foreground color.
 *
 * @param e the action event
 */
public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
        Color fg = this.fg;
        if ((e != null) && (e.getSource() == editor)) {
            String s = e.getActionCommand();
            try {
                fg = Color.decode(s);
            } catch (NumberFormatException nfe) {
            }
        }
        if (fg != null) {
            MutableAttributeSet attr = new SimpleAttributeSet();
            StyleConstants.setForeground(attr, fg);
            setCharacterAttributes(editor, attr, false);
        } else {
            UIManager.getLookAndFeel().provideErrorFeedback(editor);
        }
    }
}
 
Example 14
Source Project: netbeans   Source File: JavaViewHierarchyRandomTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSelectionAndInsertTab() throws Exception {
        loggingOn();
        RandomTestContainer container = createContainer();
        JEditorPane pane = container.getInstance(JEditorPane.class);
        Document doc = pane.getDocument();
        doc.putProperty("mimeType", "text/plain");
        ViewHierarchyRandomTesting.initRandomText(container);
        RandomTestContainer.Context context = container.context();
        DocumentTesting.insert(context, 0,
" osen   \n\n\n  esl\t\ta \t\t \n\n\nabcd\td  m\t\tabcdef\te\t\tab\tcdef\tef\tkojd p\t\t \n\n\n        t\t vpjm\ta\ngooywzmj           q\tugos\tdefy\t   i  xs    us tg z"
        );
        EditorPaneTesting.setCaretOffset(context, 64);
        EditorPaneTesting.moveOrSelect(context, SwingConstants.NORTH, false);
        EditorPaneTesting.moveOrSelect(context, SwingConstants.SOUTH, true);
        DocumentTesting.insert(context, 19, "g");
        EditorPaneTesting.moveOrSelect(context, SwingConstants.EAST, true);
        EditorPaneTesting.moveOrSelect(context, SwingConstants.NORTH, true);
        EditorPaneTesting.moveOrSelect(context, SwingConstants.WEST, true);
        EditorPaneTesting.performAction(context, pane, DefaultEditorKit.deletePrevCharAction);
        EditorPaneTesting.performAction(context, pane, DefaultEditorKit.insertTabAction);
        EditorPaneTesting.moveOrSelect(context, SwingConstants.EAST, false);
        EditorPaneTesting.typeChar(context, 'f');
    }
 
Example 15
Source Project: netbeans   Source File: TestSingleMethodSupport.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean canHandle(Node activatedNode) {
    FileObject fileObject = CommandUtils.getFileObject(activatedNode);
    if (fileObject == null) {
        return false;
    }
    PhpProject project = PhpProjectUtils.getPhpProject(fileObject);
    if (project == null) {
        return false;
    }
    final EditorCookie editorCookie = activatedNode.getLookup().lookup(EditorCookie.class);
    if (editorCookie == null) {
        return false;
    }
    JEditorPane pane = Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane>() {
        @Override
        public JEditorPane run() {
            return NbDocument.findRecentEditorPane(editorCookie);
        }

    });
    if (pane == null) {
        return false;
    }
    return getTestMethod(pane.getDocument(), pane.getCaret().getDot()) != null;
}
 
Example 16
Source Project: ramus   Source File: HTMLPrintable.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void loadPage(String url, final ActionListener listener)
        throws IOException {
    this.url = url;
    pane = new JEditorPane();
    pane.setContentType("text/html");
    pane.addPropertyChangeListener("page", new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            generate(0);
            if (listener != null)
                listener.actionPerformed(new ActionEvent(
                        HTMLPrintable.this, 0, "PageLoaded"));
        }
    });
    pane.setPage(url);
}
 
Example 17
Source Project: netbeans   Source File: InitializeOnBackgroundTest.java    License: Apache License 2.0 6 votes vote down vote up
@RandomlyFails // NB-Core-Build #1981, #1984
public void testInitializeOnBackground() throws Exception {
    support.open();
    
    class R implements Runnable {
        JEditorPane p;
        public void run() {
            p = support.getOpenedPanes()[0];
        }
    }
    R r = new R();
    SwingUtilities.invokeAndWait(r);
    assertNotNull(r.p);
    
    if (r.p.getEditorKit() instanceof NbLikeEditorKit) {
        NbLikeEditorKit nb = (NbLikeEditorKit)r.p.getEditorKit();
        assertNotNull("call method called", nb.callThread);
        if (nb.callThread.getName().contains("AWT")) {
            fail("wrong thread: " + nb.callThread);
        }
    } else {
        fail("Should use NbLikeEditorKit: " + r.p.getEditorKit());
    }
}
 
Example 18
Source Project: netbeans   Source File: MultiViewPeer.java    License: Apache License 2.0 5 votes vote down vote up
JEditorPane getEditorPane() {
    if (model != null) {
        MultiViewElement el = model.getActiveElement();
        if (el != null && el.getVisualRepresentation() instanceof Pane) {
            Pane pane = (Pane)el.getVisualRepresentation();
            return pane.getEditorPane();
        }
    }
    return null;
}
 
Example 19
Source Project: MakeLobbiesGreatAgain   Source File: GithubPanel.java    License: MIT License 5 votes vote down vote up
/**
 * Creates the new Panel and parses the supplied HTML.  <br>
 * <b> Supported Github Markdown: </b><i> Lists (unordered), Links, Images, Bold ('**' and '__'), Strikethrough, & Italics.  </i>
 *
 * @param currentVersion The version of the Jar currently running.
 */
public GithubPanel(double currentVersion) {
	this.version = currentVersion;

	setTitle("MLGA Update");
	try {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		parseReleases();
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	if (updates <= 0) {
		return;
	}
	ed = new JEditorPane("text/html", html);
	ed.setEditable(false);
	ed.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
	ed.setFont(new Font("Helvetica", 0, 12));

	ed.addHyperlinkListener(he -> {
		// Listen to link clicks and open them in the browser.
		if (he.getEventType() == EventType.ACTIVATED && Desktop.isDesktopSupported()) {
			try {
				Desktop.getDesktop().browse(he.getURL().toURI());
				System.exit(0);
			} catch (IOException | URISyntaxException e) {
				e.printStackTrace();
			}
		}
	});
	final JScrollPane scrollPane = new JScrollPane(ed);
	scrollPane.setPreferredSize(new Dimension(1100, 300));
	add(scrollPane);
	setDefaultCloseOperation(DISPOSE_ON_CLOSE);
	pack();
	setLocationRelativeTo(null);
}
 
Example 20
/**
 * Toggles the Underline attribute.
 *
 * @param e the action event
 */
public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
        StyledEditorKit kit = getStyledEditorKit(editor);
        MutableAttributeSet attr = kit.getInputAttributes();
        boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
        SimpleAttributeSet sas = new SimpleAttributeSet();
        StyleConstants.setUnderline(sas, underline);
        setCharacterAttributes(editor, sas, false);
    }
}
 
Example 21
Source Project: netbeans   Source File: WhitespaceHighlightingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    pane = new JEditorPane();
    doc = pane.getDocument();
    wh = new WhitespaceHighlighting(pane);
    wh.testInitEnv(INDENT_ATTRS, TRAILING_ATTRS);
}
 
Example 22
Source Project: netbeans   Source File: HtmlExternalDropHandler.java    License: Apache License 2.0 5 votes vote down vote up
private JEditorPane findPane(Component component) {
    while (component != null) {
        if (component instanceof JEditorPane) {
            return (JEditorPane) component;
        }
        component = component.getParent();
    }
    return null;
}
 
Example 23
Source Project: dummydroid   Source File: NavigateAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param description
 *          the textfield that holds the forms description
 * @param formContainer
 *          the container in which the editor form is sitting
 * @param type
 *          BACK or FORWARD.
 */
public NavigateAction(JEditorPane description, JPanel formContainer, int type, FormData formData) {
	this.formContainer = formContainer;
	this.type = type;
	this.formData = formData;
	if (type == BACK) {
		putValue(NAME, "back");
	}
	if (type == FORWARD) {
		putValue(NAME, "next");
	}
	this.description = description;
}
 
Example 24
Source Project: netbeans   Source File: GeneralNodeJs.java    License: Apache License 2.0 5 votes vote down vote up
protected void clickForTextPopup(EditorOperator eo, String menu) {
    JEditorPaneOperator txt = eo.txtEditorPane();
    JEditorPane epane = (JEditorPane) txt.getSource();
    try {
        Rectangle rct = epane.modelToView(epane.getCaretPosition());
        txt.clickForPopup(rct.x, rct.y);
        JPopupMenuOperator popup = new JPopupMenuOperator();
        popup.pushMenu(menu);
    } catch (BadLocationException ex) {
        System.out.println("=== Bad location");
    }
}
 
Example 25
Source Project: hottub   Source File: StyledEditorKit.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Toggles the Underline attribute.
 *
 * @param e the action event
 */
public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
        StyledEditorKit kit = getStyledEditorKit(editor);
        MutableAttributeSet attr = kit.getInputAttributes();
        boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
        SimpleAttributeSet sas = new SimpleAttributeSet();
        StyleConstants.setUnderline(sas, underline);
        setCharacterAttributes(editor, sas, false);
    }
}
 
Example 26
Source Project: marathonv5   Source File: JavaElementFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static void reset() {
    add(Component.class, JavaElement.class);
    add(JList.class, JListJavaElement.class);
    add(JTabbedPane.class, JTabbedPaneJavaElement.class);
    add(JComboBox.class, JComboBoxJavaElement.class);
    add(JTable.class, JTableJavaElement.class);
    add(JTableHeader.class, JTableHeaderJavaElement.class);
    add(JTree.class, JTreeJavaElement.class);
    add(JToggleButton.class, JToggleButtonJavaElement.class);
    add(JSpinner.class, JSpinnerJavaElement.class);
    add(JProgressBar.class, JProgressBarJavaElement.class);
    add(JSplitPane.class, JSplitPaneJavaElement.class);
    add(JTextComponent.class, JTextComponentJavaElement.class);
    add(EditorContainer.class, JTreeEditingContainerJavaElement.class);
    add(JEditorPane.class, JEditorPaneJavaElement.class);
    add(JMenuItem.class, JMenuItemJavaElement.class);
    add(JSlider.class, JSliderJavaElement.class);
    add(JSpinner.class, JSpinnerJavaElement.class);
    add(DefaultEditor.class, DefaultEditorJavaElement.class);
    add(JColorChooser.class, JColorChooserJavaElement.class);
    add(JFileChooser.class, JFileChooserJavaElement.class);
    add("com.jidesoft.swing.TristateCheckBox", JideTristateCheckBoxElement.class);
    add("com.jidesoft.swing.CheckBoxListCellRenderer", JideCheckBoxListItemElement.class);
    add("com.jidesoft.swing.CheckBoxTreeCellRenderer", JideCheckBoxTreeNodeElement.class);
    add("com.jidesoft.spinner.DateSpinner", JideDateSpinnerElement.class);
    add("com.jidesoft.swing.JideSplitPane", JideSplitPaneElement.class);
}
 
Example 27
Source Project: netbeans   Source File: ReusableEditor2Test.java    License: Apache License 2.0 5 votes vote down vote up
private int getOpenedCount(final CES ces) {
    return Mutex.EVENT.readAccess(new Mutex.Action<Integer>() {
        public Integer run() {
            JEditorPane[] panes = ces.getOpenedPanes();
            return panes == null ? 0 : panes.length;
        }
    });
}
 
Example 28
Source Project: Java8CN   Source File: StyledEditorKit.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Toggles the bold attribute.
 *
 * @param e the action event
 */
public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
        StyledEditorKit kit = getStyledEditorKit(editor);
        MutableAttributeSet attr = kit.getInputAttributes();
        boolean bold = (StyleConstants.isBold(attr)) ? false : true;
        SimpleAttributeSet sas = new SimpleAttributeSet();
        StyleConstants.setBold(sas, bold);
        setCharacterAttributes(editor, sas, false);
    }
}
 
Example 29
Source Project: netbeans   Source File: ExternalDeleteOfModifiedFileTest.java    License: Apache License 2.0 5 votes vote down vote up
private JEditorPane[] getPanes() {
    return Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane[]>() {
        public JEditorPane[] run() {
            return edit.getOpenedPanes();
        }
    });
}
 
Example 30
Source Project: netbeans   Source File: ToggleDebuggingAction.java    License: Apache License 2.0 5 votes vote down vote up
public ToggleDebuggingAction(JEditorPane pane) {
    this();
    
    assert (pane != null);
    this.pane = pane;
    actions.add(this);
    updateState();
}