Java Examples for javax.swing.text.StyledDocument

The following java examples will help you to understand the usage of javax.swing.text.StyledDocument. These source code samples are taken from different open source projects.

Example 1
Project: triple-master  File: ChatPanelTest.java View source code
@Test
public void testTrim() throws Exception {
    final StyledDocument doc = new DefaultStyledDocument();
    final StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < 10; i++) {
        buffer.append("\n");
    }
    doc.insertString(0, buffer.toString(), null);
    ChatMessagePanel.trimLines(doc, 20);
    assertEquals(doc.getLength(), 10);
    ChatMessagePanel.trimLines(doc, 10);
    assertEquals(doc.getLength(), 10);
    ChatMessagePanel.trimLines(doc, 5);
    assertEquals(doc.getLength(), 5);
    ChatMessagePanel.trimLines(doc, 1);
    assertEquals(doc.getLength(), 1);
}
Example 2
Project: antlrworks2-master  File: AbstractSemanticHighlighter.java View source code
@Override
public HighlightsLayer[] createLayers(Context context) {
    Document document = context.getDocument();
    if (!(document instanceof StyledDocument)) {
        return new HighlightsLayer[0];
    }
    AbstractSemanticHighlighter<?> highlighter = (AbstractSemanticHighlighter<?>) document.getProperty(highlighterClass);
    if (highlighter == null) {
        highlighter = createHighlighter(context);
        highlighter.initialize();
        document.putProperty(highlighterClass, highlighter);
    }
    highlighter.addComponent(context.getComponent());
    return new HighlightsLayer[] { HighlightsLayer.create(highlighterClass.getName(), getPosition(), true, highlighter) };
}
Example 3
Project: dipGame-master  File: WhiteTextArea.java View source code
public void append(String s, Color color, Boolean bold) {
    try {
        StyledDocument doc = (StyledDocument) text.getDocument();
        Style style = doc.addStyle("name", null);
        StyleConstants.setForeground(style, color);
        StyleConstants.setBold(style, bold);
        doc.insertString(doc.getLength(), s, style);
        // Determine whether the scrollbar is currently at the very bottom
        // position.
        JScrollBar vbar = scrollpane.getVerticalScrollBar();
        boolean autoScroll = ((vbar.getValue() + vbar.getVisibleAmount()) == vbar.getMaximum());
        // now scroll if we were already at the bottom.
        if (autoScroll) {
            text.setCaretPosition(text.getDocument().getLength());
        }
    } catch (BadLocationException exc) {
        exc.printStackTrace();
    }
}
Example 4
Project: goworks-master  File: AbstractSemanticHighlighter.java View source code
@Override
public HighlightsLayer[] createLayers(Context context) {
    Document document = context.getDocument();
    if (!(document instanceof StyledDocument)) {
        return new HighlightsLayer[0];
    }
    AbstractSemanticHighlighter<?> highlighter = (AbstractSemanticHighlighter<?>) document.getProperty(highlighterClass);
    if (highlighter == null) {
        highlighter = createHighlighter(context);
        highlighter.initialize();
        document.putProperty(highlighterClass, highlighter);
    }
    highlighter.addComponent(context.getComponent());
    return new HighlightsLayer[] { HighlightsLayer.create(highlighterClass.getName(), getPosition(), true, highlighter) };
}
Example 5
Project: Advanced-Logon-Editor-master  File: SaveAsDialog.java View source code
private void create(final Skin skin) {
    JPanel topPanel = new JPanel();
    topPanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    String tmp = GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_TITLE);
    topPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 0, 5), BorderFactory.createTitledBorder(tmp)));
    topPanel.setLayout(new BorderLayout());
    this.basePanel.add(topPanel);
    {
        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        JTextPane mainTextpane = new JTextPane();
        tmp = GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_MSG);
        mainTextpane.setText(tmp);
        mainTextpane.setEditable(false);
        mainTextpane.setBorder(BorderFactory.createEmptyBorder(20, 0, 10, 0));
        mainTextpane.setFont(GUIConstants.DEFAULT_MESSAGE_FONT);
        mainTextpane.setBackground(GUIConstants.DEFAULT_BACKGROUND);
        topPanel.add(mainTextpane, BorderLayout.NORTH);
        StyledDocument doc = mainTextpane.getStyledDocument();
        doc.setParagraphAttributes(0, doc.getLength(), center, false);
    }
    JPanel inputPanel = new JPanel();
    inputPanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    inputPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
    topPanel.add(inputPanel, BorderLayout.CENTER);
    inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
    JPanel inputLabelPanel = new JPanel();
    inputLabelPanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    inputLabelPanel.setBorder(new EmptyBorder(4, 0, 0, 0));
    inputLabelPanel.setLayout(new VerticalLayout(5, VerticalLayout.RIGHT));
    inputPanel.add(inputLabelPanel);
    {
        tmp = GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_NAME);
        this.lblNameLabel = new JLabel(tmp);
        this.lblNameLabel.setFont(UIManager.getFont("MenuItem.font"));
        this.lblNameLabel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
        this.lblNameLabel.setBorder(new EmptyBorder(3, 5, 0, 5));
        inputLabelPanel.add(this.lblNameLabel);
        tmp = GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_REPLACE);
        JLabel lblReplaceLabel = new JLabel(tmp);
        lblReplaceLabel.setFont(UIManager.getFont("MenuItem.font"));
        lblReplaceLabel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
        lblReplaceLabel.setBorder(new EmptyBorder(9, 5, 0, 5));
        inputLabelPanel.add(lblReplaceLabel);
    }
    JPanel inputTextfieldPanel = new JPanel();
    inputTextfieldPanel.setBorder(new EmptyBorder(5, 5, 0, 0));
    inputTextfieldPanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    inputPanel.add(inputTextfieldPanel);
    inputTextfieldPanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT));
    {
        this.textFieldName = new JTextField();
        this.textFieldName.setColumns(25);
        this.textFieldName.setText(skin.getFilename());
        this.textFieldName.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                while ((SaveAsDialog.this.textFieldName.getText().length() > 0) && (!SaveAsDialog.this.textFieldName.getText().matches(Constants.SKIN_NAME_REGEX) || (SaveAsDialog.this.textFieldName.getText().length() > Constants.SKIN_INPUT_MAXCHARS))) {
                    SaveAsDialog.this.textFieldName.setText(SaveAsDialog.this.textFieldName.getText().substring(0, SaveAsDialog.this.textFieldName.getText().length() - 1));
                }
                if (!SaveAsDialog.this.replaceSkin && !SaveAsDialog.this.textFieldName.getText().equals("") && Files.exists(Constants.PROGRAM_SKINS_PATH.resolve((SaveAsDialog.this.textFieldName.getText()).trim()), LinkOption.NOFOLLOW_LINKS)) {
                    SaveAsDialog.this.lblNameLabel.setText(SaveAsDialog.this.strNameLabel + " " + SaveAsDialog.this.strNameExistsLabel);
                    SaveAsDialog.this.textFieldName.setBackground(Color.RED);
                } else {
                    SaveAsDialog.this.textFieldName.setBackground(Color.WHITE);
                    SaveAsDialog.this.lblNameLabel.setText(SaveAsDialog.this.strNameLabel);
                }
            }
        });
        inputTextfieldPanel.add(this.textFieldName);
        final JCheckBox btnReplaceSkinButton = new JCheckBox();
        btnReplaceSkinButton.setBackground(GUIConstants.DEFAULT_BACKGROUND);
        btnReplaceSkinButton.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        btnReplaceSkinButton.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                SaveAsDialog.this.replaceSkin = btnReplaceSkinButton.isSelected();
                if (!SaveAsDialog.this.replaceSkin && !SaveAsDialog.this.textFieldName.getText().equals("") && Files.exists(Constants.PROGRAM_SKINS_PATH.resolve(SaveAsDialog.this.textFieldName.getText()), LinkOption.NOFOLLOW_LINKS)) {
                    SaveAsDialog.this.lblNameLabel.setText(SaveAsDialog.this.strNameLabel + "| " + SaveAsDialog.this.strNameExistsLabel);
                    SaveAsDialog.this.textFieldName.setBackground(Color.RED);
                } else {
                    SaveAsDialog.this.textFieldName.setBackground(Color.WHITE);
                    SaveAsDialog.this.lblNameLabel.setText(SaveAsDialog.this.strNameLabel);
                }
            }
        });
        inputTextfieldPanel.add(btnReplaceSkinButton);
    }
    JPanel buttonPanel = new JPanel();
    buttonPanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    buttonPanel.setLayout(new BorderLayout());
    this.basePanel.add(buttonPanel, BorderLayout.SOUTH);
    JPanel navbuttons = new JPanel();
    navbuttons.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    navbuttons.setLayout(new FlowLayout(FlowLayout.RIGHT));
    buttonPanel.add(navbuttons, BorderLayout.EAST);
    {
        final JButton okButton = new JButton(GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_OK));
        okButton.setBackground(GUIConstants.DEFAULT_BACKGROUND);
        okButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if ((SaveAsDialog.this.textFieldName.getText().length() <= 1) || SaveAsDialog.this.textFieldName.getText().equals("") || (!SaveAsDialog.this.replaceSkin && Files.exists(Constants.PROGRAM_SKINS_PATH.resolve(SaveAsDialog.this.textFieldName.getText()), LinkOption.NOFOLLOW_LINKS))) {
                    SaveAsDialog.this.textFieldName.setBackground(Color.RED);
                } else {
                    okButton.setEnabled(false);
                    Main.saveAs(skin, SaveAsDialog.this.textFieldName.getText());
                    dispose();
                    if (SaveAsDialog.this.checkOpenSkin.isSelected()) {
                        Main.showEditor(SaveAsDialog.this.textFieldName.getText());
                    }
                }
            }
        });
        navbuttons.add(okButton);
        JButton cancelButton = new JButton(GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_CANCEL));
        cancelButton.setBackground(GUIConstants.DEFAULT_BACKGROUND);
        cancelButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });
        navbuttons.add(cancelButton);
    }
    JPanel checkBPanel = new JPanel();
    checkBPanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    buttonPanel.add(checkBPanel, BorderLayout.WEST);
    this.checkOpenSkin = new JCheckBox(GUIStrings.keyToLocatedString(GUIStrings.KEY_SAVEASDIALOG_OPENAFTERSAVE));
    this.checkOpenSkin.setBackground(GUIConstants.DEFAULT_BACKGROUND);
    this.checkOpenSkin.setFocusable(false);
    checkBPanel.add(this.checkOpenSkin);
}
Example 6
Project: Babel-17-master  File: SyntaxErrorsHighlightingTask.java View source code
@Override
public void run(Result result, SchedulerEvent event) {
    try {
        Babel17Parser.Babel17ParserResult babel17Result = (Babel17Parser.Babel17ParserResult) result;
        Collection<ErrorMessage> syntaxErrors = babel17Result.getErrors();
        Document document = result.getSnapshot().getSource().getDocument(false);
        List<ErrorDescription> errors = new ArrayList<ErrorDescription>();
        for (ErrorMessage error : syntaxErrors) {
            Location loc = error.location().normalize();
            int start = NbDocument.findLineOffset((StyledDocument) document, loc.startLine() - 1) + loc.startColumn() - 1;
            int end = NbDocument.findLineOffset((StyledDocument) document, loc.endLine() - 1) + loc.endColumn();
            ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription(Severity.ERROR, error.message(), document, document.createPosition(start), document.createPosition(end));
            errors.add(errorDescription);
        }
        HintsController.setErrors(document, "Babel-17", errors);
        Babel17EditorStatusProvider p = (Babel17EditorStatusProvider) document.getProperty(Babel17EditorStatusProviderFactory.PROP);
        if (p != null)
            p.setStatus(UpToDateStatus.UP_TO_DATE_OK);
    } catch (BadLocationException ex1) {
    }
}
Example 7
Project: Desktop-master  File: TagToMarkedTextStore.java View source code
/** set the Style for the tag if an entry is available */
public void setStyleForTag(String tag, String style, StyledDocument doc) {
    LinkedList<TMarkedStoreItem> ll = tagMap.get(tag);
    if (ll != null) {
        // iterate over all saved selections
        for (ListIterator<TMarkedStoreItem> lIt = ll.listIterator(); lIt.hasNext(); ) {
            Object du2 = lIt.next();
            if (du2 != null) {
                TMarkedStoreItem item = (TMarkedStoreItem) du2;
                doc.setCharacterAttributes(item.start, item.end - item.start, doc.getStyle(style), true);
            }
        }
    }
}
Example 8
Project: Docear-master  File: TagToMarkedTextStore.java View source code
/** set the Style for the tag if an entry is available */
public void setStyleForTag(String tag, String style, StyledDocument doc) {
    LinkedList<TMarkedStoreItem> ll = tagMap.get(tag);
    if (ll != null) {
        // iterate over all saved selections
        for (ListIterator<TMarkedStoreItem> lIt = ll.listIterator(); lIt.hasNext(); ) {
            Object du2 = lIt.next();
            if (du2 != null) {
                TMarkedStoreItem item = (TMarkedStoreItem) du2;
                doc.setCharacterAttributes(item.start, item.end - item.start, doc.getStyle(style), true);
            }
        }
    }
}
Example 9
Project: flow-netbeans-markdown-master  File: MarkdownPreviewMVElement.java View source code
@Override
public void componentShowing() {
    final EditorCookie ec = context.lookup(EditorCookie.class);
    if (ec != null) {
        RP.post(new Runnable() {

            @Override
            public void run() {
                try {
                    final StyledDocument localSourceDoc = ec.openDocument();
                    setSourceDocument(localSourceDoc);
                    doUpdatePreview();
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    }
    htmlView.addPropertyChangeListener(htmlViewListener);
}
Example 10
Project: freemarker-support-for-netbeans-master  File: FTLCompletionProvider.java View source code
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    int lineStartOffset;
    String filter;
    // poczatek uzupelnianego slowa
    int startOffset = caretOffset - 1;
    String currentLine;
    String text;
    Set<String> idents = new HashSet<String>();
    HashMap<String, Set<String>> variables = new HashMap<String, Set<String>>();
    Token prevToken;
    TokenSequence ts;
    try {
        ((AbstractDocument) document).readLock();
        ts = TokenHierarchy.get(document).tokenSequence();
        while (ts.moveNext()) {
            Token token = ts.token();
            if (token.id().ordinal() == FMParserConstants.ID) {
                idents.add(token.text().toString());
            }
        }
        ts.move(caretOffset);
        ts.movePrevious();
        prevToken = ts.token();
        final StyledDocument bDoc = (StyledDocument) document;
        text = bDoc.getText(0, bDoc.getLength());
        // poczatek bieżącej linii
        lineStartOffset = getRowFirstNonWhite(bDoc, caretOffset);
        currentLine = getCurrentLine(bDoc, caretOffset);
        //System.out.println(currentLine);
        final char[] line = bDoc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray();
        // tekst od poczatku linii do kursora
        currentLine = String.valueOf(line);
        //System.out.println(currentLine);
        // ostatnia spacja
        final int whiteOffset = indexOfWhite(line);
        // uzupelniane slowo
        filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1);
        if (whiteOffset > 0) {
            startOffset = lineStartOffset + whiteOffset + 1;
        } else {
            startOffset = lineStartOffset;
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
        return;
    } finally {
        ((AbstractDocument) document).readUnlock();
    }
    try {
        Project project = FileOwnerQuery.getOwner(NbEditorUtilities.getFileObject(document));
        ClassPathProvider cpp = project.getLookup().lookup(ClassPathProvider.class);
        ClassPath cp = cpp.findClassPath(project.getProjectDirectory().getFileObject("src"), ClassPath.EXECUTE);
        String ftlvariable = "(<|\\[)#--\\s@ftlvariable\\sname=\"(\\w+)\"\\stype=\"((\\w+\\.)+\\w+)\"\\s--(>|\\])";
        Pattern ftlvarpattern = Pattern.compile(ftlvariable);
        Matcher ftlvarmatcher = ftlvarpattern.matcher(text);
        while (ftlvarmatcher.find()) {
            String name = ftlvarmatcher.group(2);
            String type = ftlvarmatcher.group(3);
            Set<String> varFields = variables.get(name);
            if (varFields == null) {
                varFields = new HashSet<String>();
                variables.put(name, varFields);
            }
            Class<?> typeClass = Class.forName(type, false, cp.getClassLoader(true));
            for (java.lang.reflect.Field f : typeClass.getDeclaredFields()) {
                varFields.add(f.getName());
            }
        }
    } catch (Exception ex) {
    }
    // directives
    if (currentLine.matches(".*(<|\\[)#\\w*")) {
        filter = currentLine.substring(currentLine.lastIndexOf("#") + 1);
        for (String keyword : directives) {
            if (keyword.startsWith(filter)) {
                completionResultSet.addItem(FTLCompletionItem.directive(keyword, caretOffset - filter.length(), caretOffset));
            }
        }
    } else if (currentLine.matches(".*(<|\\[)@\\w*")) {
        // unified call
        filter = currentLine.substring(currentLine.lastIndexOf("@") + 1);
        Set<String> names = new HashSet<String>();
        Pattern pattern = Pattern.compile("(<|\\[)#assign\\s+(\\w+)");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String name = matcher.group(2);
            if (name.startsWith(filter)) {
                names.add(name);
            }
        }
        pattern = Pattern.compile("(<|\\[)#import\\s.+\\sas\\s+(\\w+)");
        matcher = pattern.matcher(text);
        while (matcher.find()) {
            String name = matcher.group(2);
            if (name.startsWith(filter)) {
                names.add(name);
            }
        }
        for (String name : names) {
            completionResultSet.addItem(new FTLCompletionItem(name, caretOffset - filter.length(), caretOffset));
        }
    } else if (currentLine.matches("(<|\\[)#ftl\\s.*")) {
        filter = currentLine.substring(currentLine.lastIndexOf(' ') + 1);
        for (String param : ftlParameters) {
            if (param.startsWith(filter) && !currentLine.contains(param)) {
                completionResultSet.addItem(new FTLCompletionItem(param, "=", startOffset, caretOffset));
            }
        }
    } else if (currentLine.matches(".*(<|\\[)#setting\\s+[a-z_]*")) {
        filter = currentLine.substring(currentLine.lastIndexOf(' ') + 1);
        for (String param : settingNames) {
            if (param.startsWith(filter)) {
                completionResultSet.addItem(new FTLCompletionItem(param, "=", startOffset, caretOffset));
            }
        }
    }
    if (currentLine.matches(".*(<#|\\$\\{)[^>}]*\\w+\\?\\w*$")) {
        // builtins only inside interpolations or directives
        filter = currentLine.substring(currentLine.lastIndexOf("?") + 1);
        for (String builtin : builtins) {
            if (builtin.startsWith(filter)) {
                completionResultSet.addItem(FTLCompletionItem.builtin(builtin, lineStartOffset + currentLine.lastIndexOf("?") + 1, caretOffset));
            }
        }
    }
    if (currentLine.matches(".*\\$\\{(\\w*)")) {
        filter = currentLine.substring(currentLine.lastIndexOf("{") + 1);
        for (String ident : idents) {
            if (ident.startsWith(filter)) {
                completionResultSet.addItem(new FTLCompletionItem(ident, lineStartOffset + currentLine.lastIndexOf("{") + 1, caretOffset));
            }
        }
    }
    if (prevToken != null) {
        /*if (prevToken.id().ordinal() == FMParserConstants.DOLLAR_INTERPOLATION_OPENING) {
                     for (String ident : idents) {
                     if (ident.startsWith(filter)) {
                     completionResultSet.addItem(new FTLCompletionItem(ident, caretOffset, caretOffset));
                     }
                     }
                     }*/
        if (prevToken.id().ordinal() == FMParserConstants.DOT) {
            if (ts.movePrevious()) {
                Set<String> varFields = variables.get(ts.token().text().toString());
                if (varFields != null) {
                    for (String field : varFields) {
                        completionResultSet.addItem(new FTLCompletionItem(field, caretOffset, caretOffset));
                    }
                }
            }
        }
    }
    completionResultSet.finish();
}
Example 11
Project: jabref-master  File: TagToMarkedTextStore.java View source code
/** set the Style for the tag if an entry is available */
public void setStyleForTag(String tag, String style, StyledDocument doc) {
    List<TMarkedStoreItem> ll = tagMap.get(tag);
    if (ll != null) {
        // iterate over all saved selections
        for (TMarkedStoreItem item : ll) {
            if (item != null) {
                doc.setCharacterAttributes(item.getStart(), item.getLength(), doc.getStyle(style), true);
            }
        }
    }
}
Example 12
Project: java.old-master  File: JTextPaneAppender.java View source code
@Override
public void append(LoggingEvent event) {
    sw.getBuffer().setLength(0);
    super.append(event);
    final String message = sw.toString();
    final int logLevel = event.getLevel().toInt();
    final StyledDocument doc = textPane.getStyledDocument();
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                if (logLevel >= Level.ERROR_INT) {
                    doc.insertString(doc.getLength(), message, red);
                } else {
                    doc.insertString(doc.getLength(), message, null);
                }
            } catch (BadLocationException e) {
            }
        }
    });
}
Example 13
Project: SlingBeans-master  File: OpenEditorAction.java View source code
/*
    private synchronized void registerClasspath() throws MalformedURLException {
        if (1 == 1) {
            return;
        }
        // if (!cpRegistrated.contains("cq5")){
        File cq5libs = null;
        Set<URL> urls = new HashSet<URL>();
        StringBuilder classpathSb = new StringBuilder();
        for (File cq5lib : cq5libs.listFiles()) {
            if (cq5lib.getName().endsWith(".jar")) {
                try {
                    URL url = FileUtil.urlForArchiveOrDir(cq5lib);
                    urls.add(url);
                     if (classpathSb.length()>0){
                     classpathSb.append(File.pathSeparator);
                     }
                     classpathSb.append(cq5lib.getCanonicalPath());
                } catch (Exception ex) {
                    LogHelper.logError(ex);
                }
            }
        }
        LogHelper.logInfo(this, classpathSb.toString());
        ClassPath cq5ClassPath = ClassPathSupport.createClassPath(urls.toArray(new URL[]{}));
        GlobalPathRegistry.getDefault().register(ClassPath.COMPILE, new ClassPath[]{cq5ClassPath});
        FileObject fo = node.getFileObject();
        FileObject cpParentFo = fo.getClassPathParent();
        LogHelper.logInfo(this, "CP Parent = %s", cpParentFo.getPath());
        /*ClassPath classPath = ClassPathSupport.createClassPath(cpParentFo);
        GlobalPathRegistry gpr = GlobalPathRegistry.getDefault();
        gpr.register(ClassPath.SOURCE, new ClassPath[]{classPath});
        final ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
        LogHelper.logInfo("Source path", "%s", sourcePath);
        StringBuilder sb = new StringBuilder();
        Set<org.openide.filesystems.FileObject> sourceRoots = gpr.getSourceRoots();
        sb.append("\n\n\nSource roots:\n");
        for (org.openide.filesystems.FileObject fo2 : sourceRoots) {
            sb.append(fo2.toURL().toString());
            sb.append("\n");
        }
        sb.append("\n\n\n");
        LogHelper.logInfo(this, sb.toString());

    }*/
@Override
public void actionPerformed(ActionEvent e) {
    try {
        FileObject fo = node.getFileObject();
        DataObject d = DataObject.find(fo);
        System.out.println("Data object " + d);
        EditorCookie ec = (EditorCookie) d.getCookie(EditorCookie.class);
        if (ec != null) {
            ec.open();
            StyledDocument doc = ec.openDocument();
        } else {
            DataObject dob = DataObject.find(fo);
            Openable oc = dob.getLookup().lookup(Openable.class);
            if (oc != null) {
                oc.open();
            }
        }
    } catch (Exception ex) {
        LogHelper.logError(ex);
    }
}
Example 14
Project: SwingAppFramework-master  File: TextPaneStream.java View source code
/**
     * Write a string.  This method cannot be inherited from the Writer class
     * because it must suppress I/O exceptions.
     * @param s String to be written
     */
public void write(String s) {
    synchronized (content) {
        if (s == null) {
            s = "null";
        }
        StyledDocument doc = getText().getStyledDocument();
        int nbToRemove = doc.getLength() + s.length() - maxPrintedChar;
        try {
            if (nbToRemove > 0) {
                String begin = doc.getText(nbToRemove, nbToRemove + start);
                int line = begin.indexOf('\n');
                if (line != -1) {
                    doc.remove(0, nbToRemove + line);
                } else {
                    doc.remove(0, nbToRemove);
                }
            }
            doc.insertString(doc.getLength(), s, style);
            content.setCaretPosition(doc.getLength());
        } catch (BadLocationException ble) {
        }
    }
}
Example 15
Project: wpcleaner-master  File: MWPaneCheckWikiFormatter.java View source code
/**
   * Format Check Wiki errors in a MediaWikiPane.
   * 
   * @param doc Document to be formatted.
   * @param pageAnalysis Page analysis.
   */
private void formatCheckWikiErrors(StyledDocument doc, PageAnalysis pageAnalysis) {
    if ((doc == null) || (pageAnalysis == null) || (algorithm == null)) {
        return;
    }
    CheckErrorPage errorPage = CheckError.analyzeError(algorithm, pageAnalysis);
    if ((errorPage != null) && (errorPage.getResults() != null)) {
        int lastPosition = -1;
        List<CheckErrorResult> errorResults = errorPage.getResults();
        Collections.sort(errorResults);
        for (CheckErrorResult error : errorResults) {
            if (error.getStartPosition() >= lastPosition) {
                formatCheckWikiError(doc, error);
                lastPosition = error.getEndPosition();
            }
        }
    }
}
Example 16
Project: chartsy-master  File: AbstractCompletionItem.java View source code
public void defaultAction(final JTextComponent component) {
    final StyledDocument doc = (StyledDocument) component.getDocument();
    class AtomicChange implements Runnable {

        public void run() {
            try {
                int caretOffset = component.getCaretPosition();
                int lenght = Math.max(0, lastOffset - firstOffset + 1);
                doc.remove(firstOffset, lenght);
                doc.insertString(firstOffset, getText(), null);
            } catch (BadLocationException e) {
            }
        }
    }
    try {
        NbDocument.runAtomicAsUser(doc, new AtomicChange());
    } catch (BadLocationException e) {
    } finally {
        Completion.get().hideAll();
    }
}
Example 17
Project: codjo-segmentation-master  File: HelpStyle.java View source code
private StyledDocument buildStyles() {
    StyledDocument styledDocument = gui.getLogStyledDocument();
    Style descritionStyle = gui.addLogStyle("Description", null);
    StyleConstants.setBold(descritionStyle, true);
    StyleConstants.setUnderline(descritionStyle, true);
    StyleConstants.setForeground(descritionStyle, Color.blue);
    Style functionStyle = gui.addLogStyle("Function", null);
    StyleConstants.setForeground(functionStyle, Color.red);
    Style defaultStyle = gui.addLogStyle("Default", null);
    StyleConstants.setForeground(defaultStyle, Color.black);
    return styledDocument;
}
Example 18
Project: discobot-master  File: GroovyFilter.java View source code
public void actionPerformed(ActionEvent ae) {
    JTextComponent tComp = (JTextComponent) ae.getSource();
    if (tComp.getDocument() instanceof StyledDocument) {
        doc = (StyledDocument) tComp.getDocument();
        try {
            doc.getText(0, doc.getLength(), segment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int offset = tComp.getCaretPosition();
        int index = findTabLocation(offset);
        buffer.delete(0, buffer.length());
        buffer.append('\n');
        if (index > -1) {
            for (int i = 0; i < index + 4; i++) {
                buffer.append(' ');
            }
        }
        try {
            doc.insertString(offset, buffer.toString(), doc.getDefaultRootElement().getAttributes());
        } catch (BadLocationException ble) {
            ble.printStackTrace();
        }
    }
}
Example 19
Project: dungeon-master  File: SwappingStyledDocument.java View source code
private void writeToDocument(StyledDocument inactiveDocument, Writable writable) {
    for (ColoredString coloredString : writable.toColoredStringList()) {
        MutableAttributeSet attributeSet = new SimpleAttributeSet();
        StyleConstants.setForeground(attributeSet, coloredString.getColor());
        try {
            inactiveDocument.insertString(inactiveDocument.getLength(), coloredString.getString(), attributeSet);
        } catch (BadLocationException warn) {
            DungeonLogger.warning("insertString resulted in a BadLocationException.");
        }
    }
}
Example 20
Project: EasyPmd-master  File: GuardedSectionsAnalyzer.java View source code
private void initialize(StyledDocument document) {
    try {
        String fileContents = document.getText(0, document.getLength());
        if (fileContents.isEmpty()) {
            return;
        }
        GuardedSectionManager guardedSectionManager = GuardedSectionManager.getInstance(document);
        if (guardedSectionManager == null) {
            return;
        }
        Iterable<GuardedSection> guardedSections = guardedSectionManager.getGuardedSections();
        if (!guardedSections.iterator().hasNext()) {
            return;
        }
        int lastLineSeparatorIndex = -1;
        for (int lineNumber = 1; ; lineNumber++) {
            int lineStartIndex = lastLineSeparatorIndex + 1;
            Position lineStartPosition = document.createPosition(lineStartIndex);
            for (GuardedSection guardedSection : guardedSections) {
                if (guardedSection.contains(lineStartPosition, true)) {
                    guardedLineNumbers.add(lineNumber);
                    break;
                }
            }
            lastLineSeparatorIndex = fileContents.indexOf("\n", lastLineSeparatorIndex + 1);
            if (lastLineSeparatorIndex == -1) {
                break;
            }
        }
    } catch (BadLocationException ex) {
        throw new RuntimeException(ex);
    }
}
Example 21
Project: gMix-master  File: TextAreaConsoleAppender.java View source code
@Override
public void run() {
    StyledDocument styledDocMainLowerText;
    try {
        styledDocMainLowerText = logTextPane.getStyledDocument();
        Style style = styledDocMainLowerText.addStyle("StyledDocument", null);
        StyleConstants.setFontFamily(style, "Cursive");
        StyleConstants.setFontSize(style, 12);
        if (currentEvent.getLevel().toString() == "FATAL") {
            StyleConstants.setForeground(style, Color.red);
        } else {
            StyleConstants.setForeground(style, Color.blue);
        }
        try {
            styledDocMainLowerText.insertString(styledDocMainLowerText.getLength(), message, style);
        } catch (BadLocationException e) {
            logger.fatal(e);
        }
    } catch (Exception e) {
    }
}
Example 22
Project: groovy-core-master  File: GroovyFilter.java View source code
public void actionPerformed(ActionEvent ae) {
    JTextComponent tComp = (JTextComponent) ae.getSource();
    if (tComp.getDocument() instanceof StyledDocument) {
        doc = (StyledDocument) tComp.getDocument();
        try {
            doc.getText(0, doc.getLength(), segment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int offset = tComp.getCaretPosition();
        int index = findTabLocation(offset);
        buffer.delete(0, buffer.length());
        buffer.append('\n');
        if (index > -1) {
            for (int i = 0; i < index + 4; i++) {
                buffer.append(' ');
            }
        }
        try {
            doc.insertString(offset, buffer.toString(), doc.getDefaultRootElement().getAttributes());
        } catch (BadLocationException ble) {
            ble.printStackTrace();
        }
    }
}
Example 23
Project: groovy-master  File: GroovyFilter.java View source code
public void actionPerformed(ActionEvent ae) {
    JTextComponent tComp = (JTextComponent) ae.getSource();
    if (tComp.getDocument() instanceof StyledDocument) {
        doc = (StyledDocument) tComp.getDocument();
        try {
            doc.getText(0, doc.getLength(), segment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int offset = tComp.getCaretPosition();
        int index = findTabLocation(offset);
        buffer.delete(0, buffer.length());
        buffer.append('\n');
        if (index > -1) {
            for (int i = 0; i < index + 4; i++) {
                buffer.append(' ');
            }
        }
        try {
            doc.insertString(offset, buffer.toString(), doc.getDefaultRootElement().getAttributes());
        } catch (BadLocationException ble) {
            ble.printStackTrace();
        }
    }
}
Example 24
Project: inquisition-master  File: RichTextField.java View source code
public void caretUpdate(CaretEvent e) {
    final StyledDocument document = getStyledDocument();
    String text = getText();
    if (text.length() < 5)
        return;
    final int fooIndex = text.indexOf("foo");
    if (fooIndex < 0)
        return;
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            document.setCharacterAttributes(fooIndex, 3, getStyle("Function"), true);
        }
    });
}
Example 25
Project: jreepad-master  File: EditorPaneView.java View source code
public void updateFont(int direction) {
    StyledEditorKit kit = (StyledEditorKit) editorPane.getEditorKit();
    MutableAttributeSet set = kit.getInputAttributes();
    StyledDocument doc = (StyledDocument) editorPane.getDocument();
    Font currentFont = doc.getFont(set);
    int currentFontSize = currentFont.getSize();
    switch(direction) {
        case FontHelper.FONT_DIR_UP:
            currentFontSize++;
            break;
        case FontHelper.FONT_DIR_DOWN:
            currentFontSize--;
            break;
    }
    StyleConstants.setFontSize(set, currentFontSize);
    doc.setCharacterAttributes(0, doc.getLength(), set, false);
}
Example 26
Project: korsakow-editor-master  File: TextResourceView.java View source code
protected void initUI() {
    super.initUI();
    List<String> toolbarSequence = Arrays.asList(EkitCore.KEY_TOOL_UNDO, EkitCore.KEY_TOOL_REDO, EkitCore.KEY_TOOL_SEP, EkitCore.KEY_TOOL_BOLD, EkitCore.KEY_TOOL_ITALIC, EkitCore.KEY_TOOL_UNDERLINE, EkitCore.KEY_TOOL_FONTS, EkitCore.KEY_TOOL_SEP, EkitCore.KEY_TOOL_UNICODE, EkitCore.KEY_TOOL_ANCHOR, EkitCore.KEY_TOOL_SEP, EkitCore.KEY_TOOL_COPY, EkitCore.KEY_TOOL_PASTE);
    String sDocument = null;
    String sStyleSheet = null;
    String sRawDocument = null;
    StyledDocument sdocSource = null;
    URL urlStyleSheet = null;
    boolean includeToolBar = true;
    boolean showViewSource = false;
    boolean showMenuIcons = true;
    boolean editModeExclusive = true;
    String sLanguage = Locale.getDefault().getLanguage();
    String sCountry = Locale.getDefault().getCountry();
    boolean base64 = false;
    boolean debugMode = true;
    boolean hasSpellChecker = false;
    boolean multiBar = false;
    String toolbarSeq = Util.join(toolbarSequence, "|");
    boolean useFormatting = true;
    ekitCore = new EkitCore(sDocument, sStyleSheet, sRawDocument, sdocSource, urlStyleSheet, includeToolBar, showViewSource, showMenuIcons, editModeExclusive, sLanguage, sCountry, base64, debugMode, hasSpellChecker, multiBar, toolbarSeq, useFormatting);
    JPanel ekitPanel = new JPanel(new BorderLayout());
    ekitPanel.add(ekitCore.getToolBar(true), BorderLayout.NORTH);
    ekitPanel.add(ekitCore.getTextScrollPane(), BorderLayout.CENTER);
    mediaPanel.add(ekitPanel);
}
Example 27
Project: mirah-nbm-master  File: MirahConstructorCompletionItem.java View source code
@Override
public void defaultAction(JTextComponent jtc) {
    CodeTemplateManager mgr = CodeTemplateManager.get(jtc.getDocument());
    StringBuilder sb = new StringBuilder();
    sb.append("new");
    Class[] ptypes = method.getParameterTypes();
    if (ptypes.length > 0) {
        sb.append("(");
        for (int i = 0; i < ptypes.length; i++) {
            sb.append("${PARAM");
            sb.append(i);
            sb.append(" instanceof=\"");
            sb.append(ptypes[i].getCanonicalName());
            sb.append("\" default=\"nil\"}");
            if (i < ptypes.length - 1) {
                sb.append(", ");
            }
        }
        sb.append(")");
    }
    String tplStr = sb.toString();
    CodeTemplate tpl = mgr.createTemporary(tplStr);
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        if (length > 0) {
            doc.remove(caretOffset, length);
        }
        tpl.insert(jtc);
        //doc.insertString(caretOffset, tpl., null);
        //This statement will close the code completion box:
        Completion.get().hideAll();
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
Example 28
Project: ocelot-master  File: MatchScoreRenderer.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.swing.table.DefaultTableCellRenderer#getTableCellRendererComponent
	 * (javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
	 */
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    JTextPane textPane = new JTextPane();
    textPane.setBackground(comp.getBackground());
    textPane.setForeground(Color.white);
    textPane.setFont(comp.getFont());
    if (comp != null && value != null) {
        int score = (int) value;
        Color highlightColor = comp.getBackground();
        if (score == 100) {
            highlightColor = new Color(16, 164, 87);
        } else if (score >= 95) {
            highlightColor = new Color(95, 164, 16);
        } else if (score >= 85) {
            highlightColor = new Color(232, 206, 11);
        } else if (score >= 75) {
            highlightColor = new Color(232, 143, 11);
        } else if (score >= 65) {
            highlightColor = new Color(232, 99, 11);
        } else {
            highlightColor = new Color(232, 51, 11);
        }
        DefaultHighlightPainter painter = new DefaultHighlightPainter(highlightColor);
        StyledDocument style = textPane.getStyledDocument();
        SimpleAttributeSet rightAlign = new SimpleAttributeSet();
        StyleConstants.setAlignment(rightAlign, StyleConstants.ALIGN_RIGHT);
        try {
            style.insertString(style.getLength(), " " + value + "% ", rightAlign);
            textPane.getHighlighter().addHighlight(0, textPane.getText().length(), painter);
        } catch (BadLocationException e) {
            LOG.warn("Error while highlighting the score " + value + "at column " + column + " and row " + row + ".", e);
        }
    }
    return textPane;
}
Example 29
Project: routeKIT-master  File: AboutView.java View source code
private JPanel initTextPane() {
    JPanel text = new JPanel(new BorderLayout());
    JTextPane information = new JTextPane();
    information.setText("routeKIT, Version 0.1" + "\n" + "PSE-Projekt WS 2013/14" + "\n" + "KIT, Institut für Theoretische Informatik" + "\n" + "Algorithmik II" + "\n" + "Prof. Dr. Peter Sanders" + "\n" + "Julian Arz" + "\n" + "G. Veit Batz" + "\n" + "Dr. Dennis Luxen" + "\n" + "Dennis Schieferdecker" + "\n" + "Ⓒ 2013-2014 Kevin Birke, Felix Dörre, Fabian Hafner," + "\n" + "Lucas Werkmeister, Dominic Ziegler, Anastasia Zinkina");
    Font displayFont = new Font("Serif", Font.ROMAN_BASELINE, 18);
    StyledDocument doc = information.getStyledDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(0, doc.getLength(), center, false);
    information.setEditable(false);
    information.setFont(displayFont);
    text.add(information, BorderLayout.CENTER);
    return text;
}
Example 30
Project: xpath-util-master  File: XPathCompletionProvider.java View source code
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    try {
        final StyledDocument bDoc = (StyledDocument) document;
        String lineTilCaret = bDoc.getText(0, caretOffset);
        String lineTilCaretTrimed = lineTilCaret.trim();
        String exp;
        String filterToken;
        boolean attributeQuery;
        int slashIndex = lineTilCaret.lastIndexOf('/');
        int atIndex = lineTilCaret.lastIndexOf('@');
        int dotOffset;
        if (lineTilCaretTrimed.length() >= 2 && lineTilCaretTrimed.charAt(0) == '/' && lineTilCaretTrimed.charAt(1) == '/' && lineTilCaretTrimed.lastIndexOf('/') == 1) {
            exp = lineTilCaret.substring(0, slashIndex + 1) + "*";
            dotOffset = caretOffset - lineTilCaret.length() + exp.length() - 1;
        } else if (lineTilCaretTrimed.length() >= 1 && lineTilCaretTrimed.charAt(0) == '/' && lineTilCaretTrimed.lastIndexOf('/') == 0) {
            exp = lineTilCaret.substring(0, slashIndex + 1);
            dotOffset = caretOffset - lineTilCaret.length() + exp.length();
        } else if (slashIndex != -1 || atIndex != -1) {
            exp = lineTilCaret.substring(0, Math.max(atIndex - 1, slashIndex));
            dotOffset = caretOffset - lineTilCaret.length() + exp.length() + 1;
        } else {
            exp = "/";
            dotOffset = 0;
        }
        attributeQuery = atIndex > slashIndex;
        filterToken = lineTilCaret.substring(Math.max(slashIndex, atIndex) + 1, caretOffset);
        XPathEvaluator eval = new XPathEvaluator();
        try {
            final String xml = XPathTopComponent.getDefault().lastFocusedEditor.getText();
            NodeList list = (NodeList) eval.evaluate(exp, xml, XPathConstants.NODESET);
            if (list != null) {
                HashSet<String> set = new HashSet<String>();
                for (int b = 0; b < list.getLength(); b++) {
                    Node current = list.item(b);
                    if (attributeQuery) {
                        NamedNodeMap attributes = current.getAttributes();
                        for (int a = 0; a < attributes.getLength(); a++) {
                            String name = attributes.item(a).getNodeName();
                            if (name != null && name.startsWith(filterToken)) {
                                set.add("@" + name);
                            }
                        }
                    } else {
                        NodeList childNodes = current.getChildNodes();
                        for (int n = 0; n < childNodes.getLength(); n++) {
                            Node item = childNodes.item(n);
                            String name = item.getNodeName();
                            if (item.getNodeType() == Node.ELEMENT_NODE && name.startsWith(filterToken)) {
                                set.add(name);
                            }
                        }
                    }
                }
                for (String item : set) {
                    completionResultSet.addItem(new XPathCompletionItem(item, dotOffset, caretOffset));
                }
            } else {
                Completion.get().hideAll();
            }
        } catch (SAXException ex) {
        } catch (IOException ex) {
        } catch (XPathExpressionException ex) {
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    completionResultSet.finish();
}
Example 31
Project: aetheria-master  File: ColorFadeInTimer.java View source code
public void actionPerformed(ActionEvent evt) {
    double progress = (double) (iters * ColorFadeInTimer.this.getDelay()) / (double) duration;
    if (progress <= 0.0)
        currentColor = sourceColor;
    else if (progress >= 1.0)
        currentColor = ColorFadeInTimer.this.targetColor;
    else
        currentColor = getTransitionColor(sourceColor, ColorFadeInTimer.this.targetColor, progress);
    //System.err.println("Iter " + iters + " color " + currentColor);
    StyledDocument sd = (StyledDocument) cl.getTextArea().getDocument();
    SimpleAttributeSet colorAttrToApply = new SimpleAttributeSet();
    StyleConstants.setForeground(colorAttrToApply, currentColor);
    sd.setCharacterAttributes(ColorFadeInTimer.this.offset, ColorFadeInTimer.this.length, colorAttrToApply, false);
    if (progress >= 1.0)
        ColorFadeInTimer.this.stop();
    else
        iters++;
}
Example 32
Project: atom-game-framework-sdk-master  File: JmePaletteUtilities.java View source code
public static void insert(final String s, final JTextComponent target) throws BadLocationException {
    final StyledDocument doc = (StyledDocument) target.getDocument();
    class AtomicChange implements Runnable {

        public void run() {
            Document value = target.getDocument();
            if (value == null)
                return;
            try {
                insert(s, target, doc);
            } catch (BadLocationException e) {
            }
        }
    }
    try {
        NbDocument.runAtomicAsUser(doc, new AtomicChange());
    } catch (BadLocationException ex) {
    }
}
Example 33
Project: extweka-master  File: ReaderToTextPane.java View source code
/**
   * Sit here listening for lines of input and appending them straight
   * to the text component.
   */
public void run() {
    while (true) {
        try {
            StyledDocument doc = m_Output.getStyledDocument();
            doc.insertString(doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName()));
            m_Output.setCaretPosition(doc.getLength());
        } catch (Exception ex) {
            try {
                sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
Example 34
Project: jabref-2.9.2-master  File: TagToMarkedTextStore.java View source code
/** set the Style for the tag if an entry is available */
public void setStyleForTag(String tag, String style, StyledDocument doc) {
    LinkedList<TMarkedStoreItem> ll = tagMap.get(tag);
    if (ll != null) {
        // iterate over all saved selections
        for (ListIterator<TMarkedStoreItem> lIt = ll.listIterator(); lIt.hasNext(); ) {
            Object du2 = lIt.next();
            if (du2 != null) {
                TMarkedStoreItem item = (TMarkedStoreItem) du2;
                doc.setCharacterAttributes(item.start, item.end - item.start, doc.getStyle(style), true);
            }
        }
    }
}
Example 35
Project: JContextExplorer-master  File: CitationInfo.java View source code
//Get citation
public void getCitation() {
    // create a JTextPane + add settings
    Instructions = new JTextPane();
    Instructions.setEditable(false);
    //retrieve document, and add styles
    StyledDocument doc = Instructions.getStyledDocument();
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style b = doc.addStyle("bold", regular);
    StyleConstants.setBold(b, true);
    Style i = doc.addStyle("italic", regular);
    StyleConstants.setItalic(i, true);
    //text into document
    try {
        doc.insertString(doc.getLength(), "Citation:\n\n", doc.getStyle("bold"));
        doc.insertString(doc.getLength(), "Seitzer, P., Huynh, T. A., & Facciotti, M. T. (2013). JContextExplorer: \n", doc.getStyle("regular"));
        doc.insertString(doc.getLength(), "\ta tree-based approach to facilitate cross-species\n", doc.getStyle("regular"));
        doc.insertString(doc.getLength(), "\tgenomic context comparison.  ", doc.getStyle("regular"));
        doc.insertString(doc.getLength(), "BMC bioinformatics, 14(1), ", doc.getStyle("italic"));
        doc.insertString(doc.getLength(), "\n\t18. BMC Bioinformatics.", doc.getStyle("regular"));
        doc.insertString(doc.getLength(), " doi:10.1186/1471-2105-14-18\n", doc.getStyle("regular"));
        jp = new JPanel();
        jp.add(Instructions);
        this.add(jp);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}
Example 36
Project: jDenetX-master  File: ReaderToTextPane.java View source code
/**
   * Sit here listening for lines of input and appending them straight
   * to the text component.
   */
public void run() {
    while (true) {
        try {
            StyledDocument doc = m_Output.getStyledDocument();
            doc.insertString(doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName()));
            m_Output.setCaretPosition(doc.getLength());
        } catch (Exception ex) {
            try {
                sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
Example 37
Project: jmeld-master  File: DiffLabel.java View source code
public void init() {
    Style s;
    Style defaultStyle;
    StyledDocument doc;
    setEditable(false);
    setOpaque(false);
    // Bug in Nimbus L&F doesn't honour the opaqueness of a JLabel.
    // Setting a fully transparent color is a workaround:
    setBackground(new Color(0, 0, 0, 0));
    setBorder(null);
    defaultStyle = getStyle(StyleContext.DEFAULT_STYLE);
    doc = getStyledDocument();
    s = doc.addStyle("bold", defaultStyle);
    StyleConstants.setBold(s, true);
}
Example 38
Project: mdrill-master  File: ReaderToTextPane.java View source code
/**
   * Sit here listening for lines of input and appending them straight
   * to the text component.
   */
public void run() {
    while (true) {
        try {
            StyledDocument doc = m_Output.getStyledDocument();
            doc.insertString(doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName()));
            m_Output.setCaretPosition(doc.getLength());
        } catch (Exception ex) {
            try {
                sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
Example 39
Project: MGPWeka-master  File: ReaderToTextPane.java View source code
/**
   * Sit here listening for lines of input and appending them straight
   * to the text component.
   */
public void run() {
    while (true) {
        try {
            StyledDocument doc = m_Output.getStyledDocument();
            doc.insertString(doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName()));
            m_Output.setCaretPosition(doc.getLength());
        } catch (Exception ex) {
            try {
                sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
Example 40
Project: pdfbox-master  File: LogDialog.java View source code
public void log(String name, String level, Object o, Throwable throwable) {
    StyledDocument doc = textPane.getStyledDocument();
    String levelText;
    SimpleAttributeSet levelStyle = new SimpleAttributeSet();
    if (level.equals("fatal")) {
        levelText = "Fatal";
        StyleConstants.setForeground(levelStyle, Color.WHITE);
        StyleConstants.setBackground(levelStyle, Color.BLACK);
        fatalCount++;
    } else if (level.equals("error")) {
        levelText = "Error";
        StyleConstants.setForeground(levelStyle, new Color(0xFF291F));
        StyleConstants.setBackground(levelStyle, new Color(0xFFF0F0));
        errorCount++;
    } else if (level.equals("warn")) {
        levelText = "Warning";
        StyleConstants.setForeground(levelStyle, new Color(0x614201));
        StyleConstants.setBackground(levelStyle, new Color(0xFFFCE5));
        warnCount++;
    } else if (level.equals("info")) {
        levelText = "Info";
        StyleConstants.setForeground(levelStyle, new Color(0x203261));
        StyleConstants.setBackground(levelStyle, new Color(0xE2E8FF));
        otherCount++;
    } else if (level.equals("debug")) {
        levelText = "Debug";
        StyleConstants.setForeground(levelStyle, new Color(0x32612E));
        StyleConstants.setBackground(levelStyle, new Color(0xF4FFEC));
        otherCount++;
    } else if (level.equals("trace")) {
        levelText = "Trace";
        StyleConstants.setForeground(levelStyle, new Color(0x64438D));
        StyleConstants.setBackground(levelStyle, new Color(0xFEF3FF));
        otherCount++;
    } else {
        throw new Error(level);
    }
    SimpleAttributeSet nameStyle = new SimpleAttributeSet();
    StyleConstants.setForeground(nameStyle, new Color(0x6A6A6A));
    String shortName = name.substring(name.lastIndexOf('.') + 1);
    String message = o.toString();
    if (throwable != null) {
        StringWriter sw = new StringWriter();
        throwable.printStackTrace(new PrintWriter(sw));
        message += "\n    " + sw.toString();
        exceptionCount++;
    }
    try {
        doc.insertString(doc.getLength(), " " + levelText + " ", levelStyle);
        doc.insertString(doc.getLength(), " [" + shortName + "]", nameStyle);
        doc.insertString(doc.getLength(), " " + message + "\n", null);
    } catch (BadLocationException e) {
        throw new Error(e);
    }
    textPane.setCaretPosition(doc.getLength());
    // update status bar with new counts
    updateStatusBar();
}
Example 41
Project: pegadi-master  File: DisposalCellRenderer.java View source code
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component component = wrappedRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (column == 2 || column == 3 || column == 4 || column == 5) {
        JTextArea textArea = new JTextArea((String) value);
        textArea.setBackground(component.getBackground());
        textArea.setForeground(component.getForeground());
        textArea.setFont(component.getFont());
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setSize(table.getColumnModel().getColumn(column).getWidth(), 10000);
        textArea.setSize(textArea.getWidth(), textArea.getPreferredSize().height);
        if (textArea.getHeight() > table.getRowHeight(row)) {
            table.setRowHeight(row, textArea.getHeight());
        }
        textArea.setMargin(new Insets(3, 3, 0, 0));
        component = textArea;
    } else if (column == 6) {
        List<ArticleStatus> statuses = (List<ArticleStatus>) value;
        JTextPane pane = new JTextPane();
        pane.setBackground(component.getBackground());
        pane.setForeground(component.getForeground());
        pane.setFont(component.getFont());
        StyledDocument doc = pane.getStyledDocument();
        Style style = pane.addStyle("Style", null);
        try {
            for (int i = 0; i < statuses.size(); i++) {
                if (i > 0) {
                    StyleConstants.setBackground(style, component.getBackground());
                    doc.insertString(doc.getLength(), " \n \n", style);
                }
                ArticleStatus status = statuses.get(i);
                if (status.getColor().equals(Color.white)) {
                    StyleConstants.setBackground(style, pane.getBackground());
                } else {
                    StyleConstants.setBackground(style, status.getColor());
                }
                String s = status.getName() + " (" + model.getPage(row).getArticles().get(i).getCurrentNumberOfCharacters() + " tegn)";
                doc.insertString(doc.getLength(), s, style);
            }
        } catch (BadLocationException e) {
            log.error("error - something went wrong when showing a styled cell", e);
        }
        pane.setSize(table.getColumnModel().getColumn(column).getWidth(), 10000);
        pane.setSize(pane.getWidth(), pane.getPreferredSize().height);
        if (pane.getHeight() > table.getRowHeight(row)) {
            table.setRowHeight(row, pane.getHeight());
        }
        pane.setMargin(new Insets(3, 3, 0, 0));
        component = pane;
    }
    // If it's the page number, center it and make it bold
    if (column == 0) {
        ((JLabel) component).setHorizontalAlignment(JLabel.CENTER);
        component.setFont(component.getFont().deriveFont(component.getFont().getStyle() ^ Font.BOLD));
    }
    // Here I can check for stuff and paint the row to match it (maybe colour codes etc.)
    if (model.getPage(row).isAdOnPage()) {
        if (!isSelected)
            component.setBackground(Color.lightGray);
    } else {
        if (!isSelected)
            component.setBackground(null);
    }
    return component;
}
Example 42
Project: PF-CORE-master  File: TextPanel.java View source code
public void setText(StyledDocument doc, boolean autoScroll) {
    this.autoScroll = autoScroll;
    if (textArea == null) {
        initComponents();
    }
    // Remove from old document
    textArea.getDocument().removeDocumentListener(docListener);
    textArea.setDocument(doc);
    if (autoScroll) {
        doc.addDocumentListener(docListener);
        docListener.insertUpdate(null);
    }
}
Example 43
Project: plantuml4idea-master  File: AboutDialog.java View source code
private void about() {
    aboutEditorPane.setText("<html><body>PlantUML for Idea plugin</p><p>(c) Eugene Steinberg, 2012</p><p><a href=\"https://github.com/esteinberg/plantuml4idea\">PlantUML4idea on GitHub</a></p></body></html>");
    aboutEditorPane.addHyperlinkListener(new BrowseHyperlinkListener());
    aboutEditorPane.setOpaque(false);
    StyledDocument doc = (StyledDocument) aboutEditorPane.getDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(0, doc.getLength(), center, false);
}
Example 44
Project: rjava-interface-master  File: RDocumentStyle.java View source code
/**
     * Initializes styles that we want to use in the styled document.
     * @param document
     *          the document to initialize with R styles
     */
public static void initializeDocumentStyles(StyledDocument document) {
    // 1st create a parent font style
    Style parentStyle = document.addStyle(null, null);
    RDocumentStyle.updateBaseStyle(parentStyle);
    // styled document
    for (RDocumentStyle currentStyleEnum : RDocumentStyle.values()) {
        // have the document build a new style for us and we
        // can then update it
        Style newStyle = document.addStyle(currentStyleEnum.name(), parentStyle);
        currentStyleEnum.updateStyle(newStyle);
    }
}
Example 45
Project: rust-netbeans-master  File: NetbeansRustParser.java View source code
private List<Error> getDiagnostics() {
    FileObject file = snapshot.getSource().getFileObject();
    StyledDocument document = NbDocument.getDocument(file);
    List<RustParseMessage> parseMessages = result.getParseMessages();
    List<Error> diagnostics = new ArrayList<>(parseMessages.size());
    for (RustParseMessage message : parseMessages) {
        int startOffset = NbDocument.findLineOffset(document, message.getStartLine() - 1) + message.getStartCol();
        int endOffset = NbDocument.findLineOffset(document, message.getEndLine() - 1) + message.getEndCol();
        diagnostics.add(new DefaultError("rust.parse.message", message.getMessage(), message.getMessage(), file, startOffset, endOffset, message.getLevel().severity()));
    }
    return diagnostics;
}
Example 46
Project: sad-analyzer-master  File: ReaderToTextPane.java View source code
/**
   * Sit here listening for lines of input and appending them straight
   * to the text component.
   */
public void run() {
    while (true) {
        try {
            StyledDocument doc = m_Output.getStyledDocument();
            doc.insertString(doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName()));
            m_Output.setCaretPosition(doc.getLength());
        } catch (Exception ex) {
            try {
                sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
Example 47
Project: Tira-Teima-master  File: Alerta.java View source code
/**
	 * Faz a renderização da fonte que será mostrada no alerta
	 */
public void setFontStyle() {
    SimpleAttributeSet bSet = new SimpleAttributeSet();
    StyleConstants.setAlignment(bSet, StyleConstants.ALIGN_CENTER);
    StyleConstants.setFontFamily(bSet, "lucida bold");
    StyleConstants.setFontSize(bSet, 12);
    StyledDocument doc = getStyledDocument();
    doc.setParagraphAttributes(0, 104, bSet, false);
}
Example 48
Project: visitmeta-master  File: Log4jAppender.java View source code
@Override
protected void append(LoggingEvent pE) {
    /* No logging -> Infinity loop. */
    String vText = mLayout.format(pE);
    StyledDocument vDoc = mTextPane.getStyledDocument();
    try {
        vDoc.insertString(vDoc.getLength(), vText, null);
        scrollToBottom();
    } catch (BadLocationException e) {
        LOGGER.error(e.getMessage());
    }
}
Example 49
Project: weka-master  File: ReaderToTextPane.java View source code
/**
   * Sit here listening for lines of input and appending them straight
   * to the text component.
   */
public void run() {
    while (true) {
        try {
            StyledDocument doc = m_Output.getStyledDocument();
            doc.insertString(doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName()));
            m_Output.setCaretPosition(doc.getLength());
        } catch (Exception ex) {
            try {
                sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
Example 50
Project: yamcs-master  File: ListPacket.java View source code
void hexdump(StyledDocument hexDoc) {
    try {
        hexDoc.remove(0, hexDoc.getLength());
        for (int i = 0; i < buf.length; ) {
            // build one row of hexdump: offset, hex bytes, ascii bytes
            StringBuilder asciiBuf = new StringBuilder();
            StringBuilder hexBuf = new StringBuilder();
            hexBuf.append(HEX_CHARS.charAt(i >> 12));
            hexBuf.append(HEX_CHARS.charAt((i >> 8) & 0x0f));
            hexBuf.append(HEX_CHARS.charAt((i >> 4) & 0x0f));
            hexBuf.append(HEX_CHARS.charAt(i & 0x0f));
            hexBuf.append(' ');
            for (int j = 0; j < 16; ++j, ++i) {
                if (i < buf.length) {
                    byte b = buf[i];
                    hexBuf.append(HEX_CHARS.charAt((b >> 4) & 0x0f));
                    hexBuf.append(HEX_CHARS.charAt(b & 0x0f));
                    if ((j & 1) == 1)
                        hexBuf.append(' ');
                    char c = (b < 32) || (b > 126) ? '.' : (char) b;
                    asciiBuf.append(c);
                } else {
                    hexBuf.append((j & 1) == 1 ? "   " : "  ");
                    asciiBuf.append(' ');
                }
            }
            hexBuf.append(asciiBuf);
            hexBuf.append('\n');
            hexDoc.insertString(hexDoc.getLength(), hexBuf.toString(), hexDoc.getStyle("fixed"));
        }
    } catch (BadLocationException x) {
        System.err.println("cannot format hexdump of " + name + ": " + x.getMessage());
    }
}
Example 51
Project: damp.ekeko.snippets-master  File: PositionBounds.java View source code
/** Replaces the text contained in this range.
    * This replacement is done atomically, and so is preferable to manual inserts & removes.
    * <p>If you are running this from user-oriented code, you may want to wrap it in {@link NbDocument#runAtomicAsUser}.
    * @param text new text to insert over existing text
    * @exception IOException if any problem occurred during document loading (if that was necessary)
    * @exception BadLocationException if the positions are out of the bounds of the document
    */
public void setText(final String text) throws IOException, BadLocationException {
    final StyledDocument doc = begin.getEditorSupport().openDocument();
    final BadLocationException[] hold = new BadLocationException[] { null };
    Runnable run = new Runnable() {

        public void run() {
            try {
                int p1 = begin.getOffset();
                int p2 = end.getOffset();
                int len = text.length();
                if (len == 0) {
                    // 1) set empty string
                    if (p2 > p1)
                        doc.remove(p1, p2 - p1);
                } else {
                    // 2) set non empty string
                    if (p2 - p1 >= 2) {
                        doc.insertString(p1 + 1, text, null);
                        doc.remove(p1 + 1 + len, p2 - p1 - 1);
                        doc.remove(p1, 1);
                    } else {
                        doc.insertString(p1, text, null);
                        if (p2 > p1)
                            doc.remove(p1 + len, p2 - p1);
                    }
                }
            } catch (BadLocationException e) {
                hold[0] = e;
            }
        }
    };
    NbDocument.runAtomic(doc, run);
    if (hold[0] != null)
        throw hold[0];
}
Example 52
Project: openjdk-master  File: TextStyleChooser.java View source code
@Override
public boolean checkElement(StyledDocument doc, Element element, int offset) {
    if (bold != null) {
        if (StyleConstants.isBold(element.getAttributes()) != bold.booleanValue()) {
            return false;
        }
    }
    if (italic != null) {
        if (StyleConstants.isItalic(element.getAttributes()) != italic.booleanValue()) {
            return false;
        }
    }
    if (strike != null) {
        if (StyleConstants.isStrikeThrough(element.getAttributes()) != strike.booleanValue()) {
            return false;
        }
    }
    if (understrike != null) {
        if (StyleConstants.isUnderline(element.getAttributes()) != understrike.booleanValue()) {
            return false;
        }
    }
    if (fontSize != null) {
        if (StyleConstants.getFontSize(element.getAttributes()) != fontSize.intValue()) {
            return false;
        }
    }
    if (alignment != null) {
        if (StyleConstants.getAlignment(element.getAttributes()) != alignment.intValue()) {
            return false;
        }
    }
    if (fontFamily != null) {
        if (!StyleConstants.getFontFamily(element.getAttributes()).equals(fontFamily)) {
            return false;
        }
    }
    if (background != null) {
        if (!StyleConstants.getBackground(element.getAttributes()).equals(background)) {
            return false;
        }
    }
    if (foreground != null) {
        if (!StyleConstants.getForeground(element.getAttributes()).equals(foreground)) {
            return false;
        }
    }
    return true;
}
Example 53
Project: FreeRoute-master  File: WindowObjectInfo.java View source code
/**
     * Appends p_string to the text pane.
     * Returns false, if that was not possible.
     */
private boolean append(String p_string, String p_style) {
    javax.swing.text.StyledDocument document = text_pane.getStyledDocument();
    try {
        document.insertString(document.getLength(), p_string, document.getStyle(p_style));
    } catch (javax.swing.text.BadLocationException e) {
        System.out.println("ObjectInfoWindow.append: unable to insert text into text pane.");
        return false;
    }
    return true;
}
Example 54
Project: Freerouting-master  File: WindowObjectInfo.java View source code
/**
     * Appends p_string to the text pane.
     * Returns false, if that was not possible.
     */
private boolean append(String p_string, String p_style) {
    javax.swing.text.StyledDocument document = text_pane.getStyledDocument();
    try {
        document.insertString(document.getLength(), p_string, document.getStyle(p_style));
    } catch (javax.swing.text.BadLocationException e) {
        System.out.println("ObjectInfoWindow.append: unable to insert text into text pane.");
        return false;
    }
    return true;
}
Example 55
Project: DebugPlot-master  File: NewPlot.java View source code
private static String getIdentifier(StyledDocument doc, JEditorPane ep, int offset) {
    String t = null;
    if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) {
        t = ep.getSelectedText();
    }
    if (t != null) {
        return t;
    }
    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    try {
        javax.swing.text.Element lineElem = org.openide.text.NbDocument.findLineRootElement(doc).getElement(line);
        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText(lineStartOffset, lineLen);
        int identStart = col;
        while (identStart > 0 && (Character.isJavaIdentifierPart(t.charAt(identStart - 1)) || (t.charAt(identStart - 1) == '.'))) {
            identStart--;
        }
        int identEnd = col;
        while (identEnd < lineLen && Character.isJavaIdentifierPart(t.charAt(identEnd))) {
            identEnd++;
        }
        if (identStart == identEnd) {
            return null;
        }
        return t.substring(identStart, identEnd);
    } catch (javax.swing.text.BadLocationException e) {
        return null;
    }
}
Example 56
Project: desktopclient-java-master  File: LinkUtils.java View source code
@Override
public void mouseClicked(MouseEvent e) {
    WebTextPane textPane = (WebTextPane) e.getComponent();
    StyledDocument doc = textPane.getStyledDocument();
    Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
    if (!elem.getAttributes().isDefined(URL_ATT_NAME))
        // not a link
        return;
    int len = elem.getEndOffset() - elem.getStartOffset();
    final String url;
    try {
        url = doc.getText(elem.getStartOffset(), len);
    } catch (BadLocationException ex) {
        LOGGER.log(Level.WARNING, "can't get URL", ex);
        return;
    }
    Runnable run = new Runnable() {

        @Override
        public void run() {
            WebUtils.browseSiteSafely(fixProto(url));
        }
    };
    new Thread(run, "Link Browser").start();
}
Example 57
Project: empire-db-master  File: ServerGUI.java View source code
private void initTextAreaLogger() {
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    StyledDocument doc = txtLog.getStyledDocument();
    Style inStyle = doc.addStyle("bold", def);
    StyleConstants.setBold(inStyle, true);
    Style outStyle = doc.addStyle("bold", def);
    StyleConstants.setItalic(outStyle, true);
    PrintWriter pwIN = new PrintWriter(new DocumentWriter(txtLog.getStyledDocument(), inStyle));
    PrintWriter pwOUT = new PrintWriter(new DocumentWriter(txtLog.getStyledDocument(), outStyle));
    LoggingOutInterceptor out = new LoggingOutInterceptor(pwIN);
    LoggingInInterceptor in = new LoggingInInterceptor(pwOUT);
    this._sControl.appendLogger(out, in);
}
Example 58
Project: enclojure-master  File: ClojureIndentFactory.java View source code
public void reindent() throws BadLocationException {
    StyledDocument doc = (StyledDocument) _ctx.document();
    final int indentSize = 2;
    if (!_ctx.isIndent()) {
        Node[] n = TopComponent.getRegistry().getActivatedNodes();
        if (n.length == 1) {
            EditorCookie ec = n[0].getCookie(EditorCookie.class);
            if (ec != null) {
                JEditorPane[] panes = ec.getOpenedPanes();
                if (panes.length > 0) {
                    if (panes[0].getSelectedText() == null || panes[0].getSelectedText().trim() == "") {
                        int nLineStart = _ctx.lineStartOffset(panes[0].getCaretPosition());
                        String codeAbove = doc.getText(java.lang.Math.max(0, nLineStart - PREV_CONTEXT_COUNT), java.lang.Math.min(nLineStart, PREV_CONTEXT_COUNT));
                        int indentLevel = getIndentLevel(codeAbove, indentSize);
                        _ctx.modifyIndent(nLineStart, indentLevel);
                        return;
                    }
                }
            }
        }
        int nStartOfLine = 0;
        int nLastStartOfLine = 0;
        String codeAbove = doc.getText(java.lang.Math.max(0, _ctx.lineStartOffset(_ctx.startOffset()) - PREV_CONTEXT_COUNT), java.lang.Math.min(_ctx.lineStartOffset(_ctx.startOffset()), PREV_CONTEXT_COUNT));
        while (nStartOfLine != -1) {
            int nIndentLevel = getIndentLevel(codeAbove, indentSize);
            if (nIndentLevel != _ctx.lineIndent(_ctx.lineStartOffset(_ctx.startOffset()) + nStartOfLine))
                _ctx.modifyIndent(_ctx.lineStartOffset(_ctx.startOffset()) + nStartOfLine, nIndentLevel);
            nLastStartOfLine = nStartOfLine;
            String codeBlock = doc.getText(_ctx.lineStartOffset(_ctx.startOffset()), _ctx.endOffset() - _ctx.startOffset());
            nStartOfLine = codeBlock.indexOf('\n', nStartOfLine);
            if (nStartOfLine >= 0) {
                ++nStartOfLine;
                codeAbove = doc.getText(java.lang.Math.max(0, _ctx.lineStartOffset(_ctx.startOffset()) + nStartOfLine - PREV_CONTEXT_COUNT), java.lang.Math.min(_ctx.lineStartOffset(_ctx.startOffset()) + nStartOfLine, PREV_CONTEXT_COUNT));
            }
        }
    } else {
        int nLineStart = _ctx.startOffset();
        String codeAbove = doc.getText(java.lang.Math.max(0, nLineStart - PREV_CONTEXT_COUNT), java.lang.Math.min(nLineStart, PREV_CONTEXT_COUNT));
        int indentLevel = getIndentLevel(codeAbove, indentSize);
        _ctx.modifyIndent(nLineStart, indentLevel);
    }
}
Example 59
Project: freedots-master  File: BraillePane.java View source code
/** Inserts braille signs of the transcription in the document, with
   *  different colors corresponding to each braille sign.
   */
private void insertBrailleList(final BrailleList strings, final Style parent, final StyledDocument document) {
    for (BrailleSequence seq : strings) {
        if (seq instanceof Sign) {
            Sign sign = (Sign) seq;
            Style style = document.addStyle(null, parent);
            StyleConstants.setForeground(style, SignColorMap.DEFAULT.get(sign));
            try {
                document.insertString(document.getLength(), sign.toString(), style);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        } else
            insertBrailleList((BrailleList) seq, parent, document);
    }
}
Example 60
Project: Gaalop-master  File: SourceFilePanel.java View source code
void formatCode(String content) {
    try {
        StyledDocument doc = textPane.getStyledDocument();
        Matcher matcher = PATTERN.matcher(content);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String keyword = matcher.group();
            doc.setCharacterAttributes(start, end - start, KEYWORDS.get(keyword), false);
        }
    } catch (Exception e) {
        System.err.println(e);
        textPane.setText(content);
    }
}
Example 61
Project: jMemorize-master  File: FormattedTextTest.java View source code
/**
     * Asserts that the style is still set correctly on a styled document after
     * encoding the document into a string representation and decoding it back
     * into a styled document again.
     */
public void assertStyleRoundtrip(Object style) throws BadLocationException {
    m_doc.insertString(0, "Foobar Test", SimpleAttributeSet.EMPTY);
    SimpleAttributeSet actualAttr = new SimpleAttributeSet();
    actualAttr.addAttribute(style, Boolean.TRUE);
    m_doc.setCharacterAttributes(2, 2, actualAttr, true);
    StyledDocument doc = roundtrip(m_doc);
    AttributeSet exceptedAttr = doc.getCharacterElement(2).getAttributes();
    Boolean hasStyle = (Boolean) exceptedAttr.getAttribute(style);
    if (hasStyle != null) {
        assertTrue(hasStyle.booleanValue());
    } else {
        fail("Style not set");
    }
}
Example 62
Project: JRichTextEditor-master  File: UnderlineHighlightPainter.java View source code
public void doText(final int offs0, final int offs1, JTextComponent c) {
// This won't work. The software hangs on changing the character attributes
// directly during highlight painting. So maybe it is possible to post an event
// here. Yes, let's do that.
// NO That doesn't provide us with the wanted results either!
// WE SOLVED THIS ELSEWHERE!
/*Color textColor=_provider.textColor(_mark);
      if (textColor==null) { return; }
      Document doc=c.getDocument();
      if (doc instanceof StyledDocument) {
        final StyledDocument sdoc=(StyledDocument) doc;
        final SimpleAttributeSet set=new SimpleAttributeSet();
        StyleConstants.setForeground(set, textColor);
        Runnable r=new Runnable() {
            public void run() {
                sdoc.setCharacterAttributes(offs0, offs1, set, false);
            }
        };
        SwingUtilities.invokeLater(r);
      }*/
}
Example 63
Project: jstk-master  File: AboutDialog.java View source code
protected void insertText(String text, AttributeSet set) {
    try {
        Document doc = textPane.getDocument();
        int oldLength = doc.getLength();
        doc.insertString(oldLength, text + newLine, set);
        ((StyledDocument) doc).setParagraphAttributes(oldLength, doc.getLength() - oldLength, set, false);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}
Example 64
Project: mah-master  File: TextItemPane.java View source code
private StyledDocument createNormalDocument(String text) {
    StyledDocument document = new DefaultStyledDocument();
    try {
        Style style = theme != null ? theme.getNormalTextStyle() : null;
        document.insertString(0, text, style);
        return document;
    } catch (BadLocationException e) {
        throw new UiException(e);
    }
}
Example 65
Project: nb-springboot-configuration-support-master  File: SpringBootConfigurationCompletionProvider.java View source code
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    String filter = null;
    int startOffset = caretOffset - 1;
    try {
        final StyledDocument bDoc = (StyledDocument) document;
        final int lineStartOffset = getRowFirstNonWhite(bDoc, caretOffset);
        final char[] line = bDoc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray();
        final int whiteOffset = indexOfWhite(line);
        filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1);
        if (whiteOffset > 0) {
            startOffset = lineStartOffset + whiteOffset + 1;
        } else {
            startOffset = lineStartOffset;
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    for (ConfigurationMetadata configurationMeta : configurationMetas) {
        for (ItemMetadata item : configurationMeta.getItems()) {
            if (item.isOfItemType(ItemMetadata.ItemType.PROPERTY) && !item.getName().equals("") && item.getName().startsWith(filter)) {
                completionResultSet.addItem(new SpringBootConfigurationCompletionItem(item, cp, startOffset, caretOffset));
            }
        }
    }
    completionResultSet.finish();
}
Example 66
Project: nb-yii-plugin-master  File: YiiCompletionItem.java View source code
@Override
public void defaultAction(JTextComponent jtc) {
    StyledDocument document = (StyledDocument) jtc.getDocument();
    try {
        document.remove(startOffset, removeLength);
        document.insertString(startOffset, text, null);
        Completion.get().hideAll();
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
Example 67
Project: NBStudio-master  File: macCodeCompletion.java View source code
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    String filter;
    int startOffset;
    try {
        final StyledDocument bDoc = (StyledDocument) document;
        final int lineStartOffset = getRowFirstNonWhite(bDoc, caretOffset);
        final char[] line = bDoc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray();
        final int whiteOffset = indexOfWhite(line);
        filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1);
        filter = filter.toLowerCase();
        if (whiteOffset > 0) {
            startOffset = lineStartOffset + whiteOffset + 1;
        } else {
            startOffset = lineStartOffset;
        }
        String[] keywords = new String[] { "ClassMethod", "Method", "Property", "Parameter", "Index" };
        for (String keyword : keywords) {
            if (!keyword.equals("") && keyword.toLowerCase().startsWith(filter)) {
                completionResultSet.addItem(new clsCompletionItem(keyword, startOffset, caretOffset));
            }
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    completionResultSet.finish();
}
Example 68
Project: netbeans-mmd-plugin-master  File: MMDEditorSupport.java View source code
public String getDocumentText() {
    if (this.getDataObject().isValid()) {
        try {
            final StyledDocument doc = this.openDocument();
            return doc.getText(0, doc.getLength());
        } catch (Exception ex) {
            LOGGER.error("Can't get document text", ex);
            return null;
        }
    } else {
        LOGGER.warn("DataObject " + this.getDataObject() + " is not valid");
        return null;
    }
}
Example 69
Project: netbeans-plugin-master  File: CiCompleterView.java View source code
@Override
public void defaultAction(JTextComponent jtc) {
    try {
        final StyledDocument doc = (StyledDocument) jtc.getDocument();
        // Replace existing text with complete frase.
        doc.remove(startIndex, removeLength);
        doc.insertString(startIndex, text, null);
        jtc.setCaretPosition(startIndex + text.length());
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    Completion.get().hideAll();
}
Example 70
Project: OmegaT-master  File: FontFallbackListener.java View source code
private void doStyling(Document document, final int offset, final int length) {
    if (!Preferences.isPreference(Preferences.FONT_FALLBACK)) {
        return;
    }
    if (!(document instanceof StyledDocument)) {
        return;
    }
    final StyledDocument doc = (StyledDocument) document;
    new SwingWorker<Void, StyleRun>() {

        @Override
        protected Void doInBackground() throws Exception {
            Segment seg = new Segment();
            seg.setPartialReturn(true);
            int nleft = length;
            int offs = offset;
            try {
                while (nleft > 0) {
                    doc.getText(offs, nleft, seg);
                    int i = seg.getBeginIndex();
                    while ((i = defaultFont.canDisplayUpTo(seg, i, seg.getEndIndex())) != -1) {
                        int cp = Character.codePointAt(seg, i - seg.getBeginIndex());
                        int start = i;
                        i += Character.charCount(cp);
                        Font font = FontFallbackManager.getCapableFont(cp);
                        if (font == null) {
                            continue;
                        }
                        // Look ahead to try to group as many characters as possible into this run.
                        for (int cpn, ccn, j = i; j < seg.getEndIndex(); j += ccn) {
                            cpn = Character.codePointAt(seg, j - seg.getBeginIndex());
                            ccn = Character.charCount(cpn);
                            if (!defaultFont.canDisplay(cpn) && font.canDisplay(cpn)) {
                                i += ccn;
                            } else {
                                break;
                            }
                        }
                        publish(new StyleRun(start, i - start, getAttributes(font)));
                    }
                    nleft -= seg.count;
                    offs += seg.count;
                }
            } catch (BadLocationException ex) {
            }
            return null;
        }

        protected void process(List<StyleRun> chunks) {
            for (StyleRun chunk : chunks) {
                doc.setCharacterAttributes(chunk.start, chunk.length, chunk.attrs, false);
            }
        }

        ;
    }.execute();
}
Example 71
Project: openflexo-master  File: AutoSpellEditorKit.java View source code
@Override
public void actionPerformed(ActionEvent evt) {
    SimpleAttributeSet attr;
    int pos = pane.getCaretPosition();
    if (pos < 0) {
        return;
    }
    attr = new SimpleAttributeSet(((StyledDocument) pane.getDocument()).getCharacterElement(pos).getAttributes());
    attr.addAttribute(wordMisspelled, wordMisspelledTrue);
    ((JTextPane) pane).setCharacterAttributes(attr, false);
}
Example 72
Project: openmicroscopy-master  File: ChemicalNameFormatter.java View source code
/**
     * Parse the document, find the regex matches and apply the appropriate 
     * Style to each. The Source of the Edit Event should be a 
     * StyledDocument in order that the styles are applied. 
     * Method is public so that it can be called to apply styles before any
     * editing occurs. 
     * Editing occurs on a new thread, so that concurrent editing does not 
     * occur when this method is called from a Document Listener.
     *
     * @param document The document style
     * @param refreshStyle Pass <code>true</code> to refresh the style,
     *                     <code>false</code> otherwise.
     */
public void parseRegex(StyledDocument document, boolean refreshStyle) {
    doc = document;
    refresh = refreshStyle;
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            // first, make all the text plain.
            if (refresh)
                doc.setCharacterAttributes(0, doc.getLength(), plainText, true);
            try {
                String text = doc.getText(0, doc.getLength());
                List<Position> positionList = new ArrayList<Position>();
                for (String formula : formulas) {
                    positionList.clear();
                    WikiView.findExpressions(text, formula, positionList);
                    // paint the regex
                    int start, end;
                    for (Position p : positionList) {
                        start = p.getStart();
                        end = p.getEnd();
                        Character c;
                        while (start < end) {
                            c = doc.getText(start, 1).charAt(0);
                            if (Character.isDigit(c)) {
                                doc.setCharacterAttributes(start, 1, subscript, false);
                            }
                            start++;
                        }
                    }
                }
            } catch (BadLocationException e1) {
                e1.printStackTrace();
            }
        }
    });
}
Example 73
Project: PleoCommand-master  File: LogTableCellRenderer.java View source code
private void deHTML(final JTextPane tp, final String text) throws BadLocationException {
    tp.setText("");
    final StyledDocument sd = tp.getStyledDocument();
    Style style = sd.getStyle(StyleContext.DEFAULT_STYLE);
    if (!text.startsWith("<html>")) {
        sd.insertString(0, text, style);
        return;
    }
    StringBuilder sb = new StringBuilder();
    int offset = 0;
    for (int i = 0; i < text.length(); ++i) {
        final char c = text.charAt(i);
        switch(c) {
            case '<':
                {
                    sd.insertString(offset, sb.toString(), style);
                    offset += sb.length();
                    sb = new StringBuilder();
                    final StringBuilder sb2 = new StringBuilder();
                    char c2;
                    while ((c2 = text.charAt(++i)) != '>') sb2.append(c2);
                    final String tag = sb2.toString();
                    if ("/font".equals(tag) || "/b".equals(tag) || "/i".equals(tag))
                        // we don't support recursive attributes, so just ...
                        style = sd.getStyle(StyleContext.DEFAULT_STYLE);
                    else if (tag.startsWith("b")) {
                        style = sd.addStyle(null, style);
                        StyleConstants.setBold(style, true);
                    } else if (tag.startsWith("i")) {
                        style = sd.addStyle(null, style);
                        StyleConstants.setItalic(style, true);
                    } else if (tag.startsWith("font color=#")) {
                        style = sd.addStyle(null, style);
                        StyleConstants.setForeground(style, StringManip.hexToColor(tag.substring(12)));
                    } else if ("html".equals(tag) || "/html".equals(tag)) {
                    // just ignore them silently
                    } else
                        Log.detail("Ignoring unknown tag '%s'", tag);
                    break;
                }
            case '&':
                {
                    final StringBuilder sb2 = new StringBuilder();
                    char c2;
                    while ((c2 = text.charAt(++i)) != ';') sb2.append(c2);
                    final String id = sb2.toString();
                    if ("lt".equals(id))
                        sb.append('<');
                    else if ("gt".equals(id))
                        sb.append('>');
                    else if ("amp".equals(id))
                        sb.append('&');
                    else if ("quot".equals(id))
                        sb.append('"');
                    else
                        Log.detail("Ignoring unknown &%s;", id);
                    break;
                }
            default:
                sb.append(c);
        }
    }
    sd.insertString(offset, sb.toString(), style);
}
Example 74
Project: praxis-live-master  File: PXJavaEditorSupport.java View source code
@Override
protected void loadFromStreamToKit(StyledDocument doc, InputStream stream, EditorKit kit) throws IOException, BadLocationException {
    LOG.fine("Loading PXJ Java proxy with guarded sections");
    FileObject file = dob.getPrimaryFile();
    if (guardedEditor == null) {
        guardedEditor = new GuardedEditor();
        GuardedSectionsFactory factory = GuardedSectionsFactory.find("text/x-java");
        if (factory != null) {
            LOG.fine("Found GuardedSectionsFactory");
            guardedProvider = factory.create(guardedEditor);
        }
    }
    if (guardedProvider != null) {
        LOG.fine("Loading file through GuardedSectionsProvider");
        guardedEditor.doc = doc;
        Charset c = FileEncodingQuery.getEncoding(file);
        Reader reader = guardedProvider.createGuardedReader(stream, c);
        try {
            kit.read(reader, doc, 0);
        } finally {
            reader.close();
        }
    } else {
        super.loadFromStreamToKit(doc, stream, kit);
    }
}
Example 75
Project: PSE-master  File: ChatWindow.java View source code
private void addStylesToDocument(StyledDocument doc) {
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    for (int i = 0; i < 8; i++) {
        Style newStyle = doc.addStyle("color" + i, def);
        StyleConstants.setForeground(newStyle, PlayerColor.getBackGroundColor(i));
    }
}
Example 76
Project: QuickOpener-NetBeans-master  File: RunCommand.java View source code
private Map<String, String> createPlaceholders() {
    String currentFile = PathFinder.getActivePath(null, false);
    String currentFolder = PathFinder.getActivePath(null, true);
    String relativeFile = PathFinder.getRelativeActivePath(null, false);
    String relativeFolder = PathFinder.getRelativeActivePath(null, true);
    String currentProjectFolder = PathFinder.getActiveProject();
    String mainProjectFolder = PathFinder.getMainProjectRootPath();
    Map<String, String> placeholders = new LinkedHashMap<String, String>();
    if (null != currentFile && new File(currentFile).exists()) {
        File file = new File(currentFile);
        FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(file));
        placeholders.put("${fileNameExt}", fo.getNameExt());
        placeholders.put("${fileName}", fo.getName());
        placeholders.put("${fileExt}", fo.getExt());
    } else {
        placeholders.put("${fileNameExt}", "");
        placeholders.put("${fileName}", "");
        placeholders.put("${fileExt}", "");
    }
    //${line}:${column} ${line0}:${column0} '${selectedText}' ${fileNameExt} ${fileName} ${fileExt} ${file} ${folder} ${relativeFile} ${relativeFolder} ${projectFolder} ${mainProjectFolder}
    placeholders.put("${file}", currentFile);
    placeholders.put("${folder}", currentFolder);
    placeholders.put("${relativeFile}", relativeFile);
    placeholders.put("${relativeFolder}", relativeFolder);
    placeholders.put("${projectFolder}", currentProjectFolder);
    placeholders.put("${mainProjectFolder}", mainProjectFolder);
    JTextComponent editor = getCurrentEditor();
    int caret = (null != editor) ? editor.getCaretPosition() : -1;
    StyledDocument sdocument = (null != editor && (editor.getDocument() instanceof StyledDocument)) ? (StyledDocument) editor.getDocument() : null;
    if (null != sdocument) {
        int line0 = NbDocument.findLineNumber(sdocument, caret);
        int column0 = NbDocument.findLineColumn(sdocument, caret);
        String selectedText = editor.getSelectedText();
        placeholders.put("${line0}", "" + line0);
        placeholders.put("${line}", "" + (line0 + 1));
        placeholders.put("${column0}", "" + column0);
        placeholders.put("${column}", "" + (column0 + 1));
        placeholders.put("${selectedText}", null != selectedText ? selectedText : "");
    } else {
        // add defaults for editor related placeholders
        placeholders.put("${line0}", "");
        placeholders.put("${line}", "");
        placeholders.put("${column0}", "");
        placeholders.put("${column}", "");
        placeholders.put("${selectedText}", "");
    }
    return placeholders;
}
Example 77
Project: rgfontmap-master  File: RGFontMapFrame.java View source code
private JTextPane createTextPane(String sampleText, String[] fonts, int fontSize) {
    JTextPane textPane = new JTextPane();
    StyledDocument document = textPane.getStyledDocument();
    textPane.setEditable(false);
    stylizeDocument(document, fonts, fontSize);
    try {
        for (int i = 0; i < fonts.length; i++) {
            String s = fonts[i];
            document.insertString(document.getLength(), createPrefix(s), document.getStyle("fontstyle"));
            document.insertString(document.getLength(), prepareSampleText(sampleText, s, fontSize), document.getStyle(s));
        }
    } catch (BadLocationException e) {
        System.err.println("Couldn't insert initial text into text pane.");
    }
    return textPane;
}
Example 78
Project: Scute-master  File: FindDialog.java View source code
private boolean findNext() {
    try {
        boolean matchCase = caseCheckBox.isSelected();
        String findWhat = findTextField.getText();
        StyledDocument doc = (StyledDocument) editorPane.getDocument();
        String htmlText = doc.getText(0, doc.getLength());
        if (matchCase) {
            lastMatchPos = htmlText.indexOf(findWhat, lastMatchPos + 1);
        } else {
            lastMatchPos = htmlText.toUpperCase().indexOf(findWhat.toUpperCase(), lastMatchPos + 1);
        }
        if (lastMatchPos != -1) {
            editorPane.setCaretPosition(lastMatchPos + findWhat.length());
            editorPane.requestFocus();
            editorPane.select(lastMatchPos, lastMatchPos + findWhat.length());
        }
        return lastMatchPos != -1;
    } catch (BadLocationException exception) {
        Log.exception(exception);
    }
    return false;
}
Example 79
Project: studio-master  File: EditorSupportLineSet.java View source code
/** Creates a Line for given offset.
    * @param offset the begining of line
    * @return line that should represent the given line
    */
public Line createLine(int offset) {
    StyledDocument doc = support.getDocument();
    if (doc == null)
        // do nothing - document was probably closed
        return null;
    PositionRef ref = new PositionRef(support.getPositionManager(), offset, Position.Bias.Forward);
    return new SupportLine(support.getDataObjectHack(), ref, support);
}
Example 80
Project: SwingBox-master  File: MouseController.java View source code
@Override
public void mouseMoved(MouseEvent e) {
    JEditorPane editor = (JEditorPane) e.getSource();
    if (!editor.isEditable()) {
        Bias[] bias = new Bias[1];
        Point pt = new Point(e.getX(), e.getY());
        int pos = editor.getUI().viewToModel(editor, pt, bias);
        if (bias[0] == Position.Bias.Backward && pos > 0)
            pos--;
        if (pos >= 0 && (editor.getDocument() instanceof StyledDocument)) {
            Element elem = ((StyledDocument) editor.getDocument()).getCharacterElement(pos);
            Object bb = elem.getAttributes().getAttribute(Constants.ATTRIBUTE_BOX_REFERENCE);
            Anchor anchor = (Anchor) elem.getAttributes().getAttribute(Constants.ATTRIBUTE_ANCHOR_REFERENCE);
            if (elem != prevElem) {
                prevElem = elem;
                if (!anchor.isActive()) {
                    if (bb != null && bb instanceof TextBox)
                        setCursor(editor, textCursor);
                    else
                        setCursor(editor, defaultCursor);
                }
            }
            if (anchor != prevAnchor) {
                if (prevAnchor == null) {
                    if (anchor.isActive()) {
                        createHyperLinkEvent(editor, elem, anchor, EventType.ENTERED);
                    }
                    prevAnchor = anchor;
                } else if (!prevAnchor.equalProperties(anchor.getProperties())) {
                    if (prevAnchor.isActive()) {
                        createHyperLinkEvent(editor, prevElem, prevAnchor, EventType.EXITED);
                    }
                    if (anchor.isActive()) {
                        createHyperLinkEvent(editor, elem, anchor, EventType.ENTERED);
                    }
                    prevAnchor = anchor;
                }
            }
        } else //nothing found
        {
            prevElem = null;
            if (prevAnchor != null && prevAnchor.isActive()) {
                createHyperLinkEvent(editor, prevElem, prevAnchor, EventType.EXITED);
                prevAnchor = null;
            }
            setCursor(editor, defaultCursor);
        }
    }
}
Example 81
Project: Thud-master  File: JTextPaneWriter.java View source code
public void flush() {
    synchronized (lock) {
        final StyledDocument doc = getDocument();
        if (buffer.size() == 0) {
            // FIXME: This is a hack to force scroll until
            // all writes go through this writer.
            // TODO: Add a flag to turn scrolling on/off.
            textPane.setCaretPosition(doc.getLength());
            return;
        }
        try {
            doc.insertString(doc.getLength(), buffer.toString(), textPane.getStyle(currStyle));
            // TODO: Add a flag to turn scrolling on/off.
            textPane.setCaretPosition(doc.getLength());
        } catch (final BadLocationException e) {
            System.err.println("Flush failed: " + e);
        }
        buffer.reset();
    }
}
Example 82
Project: trait_workflow_runner-master  File: RandomLinesGuiExampleTest.java View source code
/**
     * Run the workflow and check the results.
     *
     * @param guiExample the GUI example object.
     * @param frame the frame that contains the GUI.
     * @throws BadLocationException if retrieving the results from the GUI failed.
     */
private void checkRunningWorkflow(final RandomLinesGuiExample guiExample, final JFrame frame) throws BadLocationException {
    final JButton button = findButton(frame);
    if (button != null) {
        assertEquals("Run workflow", button.getText());
        assertEquals(1, button.getActionListeners().length);
        guiExample.runWorkflow(true);
        final JTextPane textPane = findTextPane(frame);
        assertNotNull(textPane);
        final String expectedRegularExpression = "Running workflow \"RandomLinesTwice\"...\n" + "\n" + "\n" + "The workflow ran successfully in " + ".*" + " and produced the following output:\n" + "\n" + "======\n" + "7\n" + "6\n" + "======\n";
        final StyledDocument document = textPane.getStyledDocument();
        final String results = document.getText(0, document.getLength());
        assertTrue("Results " + results.replaceAll("\n", "|") + " should match the pattern " + expectedRegularExpression + ".", Pattern.compile(expectedRegularExpression).matcher(results).matches());
    }
}
Example 83
Project: vizzy-master  File: CodeForm.java View source code
public void initStyles(Font font, Color foreground, Color background) {
    StyledDocument doc = jCodeTextPane.getStyledDocument();
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style boldStyleName = doc.addStyle("bold", def);
    StyleConstants.setBold(boldStyleName, true);
    StyleConstants.setForeground(boldStyleName, Color.RED);
    jCodeTextPane.setFont(font);
    jCodeTextPane.setForeground(foreground);
    jCodeTextPane.setBackground(background);
}
Example 84
Project: VUE-master  File: XMLView.java View source code
public void actionPerformed(ActionEvent e) {
    System.out.println("Action[" + e.getActionCommand() + "] invoked...");
    if (VUE.getTabbedPane().getSelectedComponent() instanceof MapViewer) {
        ActionUtil.marshallMap(new File(fileName));
        //create html view from default.xml
        File xmlFile = new File(fileName);
        xmlArea = new XMLTextPane();
        doc = (StyledDocument) xmlArea.getDocument();
        xmlArea.setText("");
        xmlArea.setEditable(false);
        xmlArea.setFont(new Font("SansSerif", Font.PLAIN, 14));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        org.w3c.dom.Document xmlDoc = null;
        try {
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            xmlDoc = documentBuilder.parse(fileName);
        } catch (Exception ex) {
            System.out.println("problem creating dom object from xml file: " + ex);
        }
        try {
            xmlArea.setText(docToString(xmlDoc));
        } catch (TransformerException te) {
            System.out.println("transformer exception: " + te);
        }
        JScrollPane pane = new JScrollPane(xmlArea);
        String mapName = VUE.getActiveMap().getLabel();
        JTabbedPane tabPane = VUE.getTabbedPane();
        for (int i = 0; i < tabPane.getComponentCount(); i++) {
            if (tabPane.getTitleAt(i).equals(mapName + ".xml")) {
                VUE.getTabbedPane().setSelectedIndex(i);
                return;
            }
        }
        VUE.getTabbedPane().addTab(mapName + ".xml", pane);
        VUE.getTabbedPane().setSelectedIndex(VUE.getTabbedPane().getComponentCount() - 1);
        //setAttributes();
        pane.repaint();
        System.out.println("Action[" + e.getActionCommand() + "] completed.");
    }
}
Example 85
Project: addis-master  File: AuxComponentFactory.java View source code
public static JComponent createNoteView(Note note, boolean scrollable) {
    JTextPane area = new JTextPane();
    StyledDocument doc = area.getStyledDocument();
    AddStudyWizard.addStylesToDoc(doc);
    area.setBackground(COLOR_NOTE);
    try {
        switch(note.getSource()) {
            case CLINICALTRIALS:
                doc.insertString(doc.getLength(), NCT_NOTE + "\n", doc.getStyle("bold"));
                break;
            case MANUAL:
                doc.insertString(doc.getLength(), USER_NOTE + "\n", doc.getStyle("bold"));
                break;
        }
        doc.insertString(doc.getLength(), (String) note.getText(), doc.getStyle("regular"));
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
    area.setEditable(false);
    if (!scrollable) {
        area.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(4, 4, 4, 4)));
        return area;
    }
    return putTextPaneInScrollPane(area);
}
Example 86
Project: BayesGame-master  File: GameInterface.java View source code
private void writeToTextPane(String text) {
    SimpleAttributeSet style = new SimpleAttributeSet();
    StyleConstants.setFontSize(style, BayesGame.getNewFontSizeInt());
    text = text + System.getProperty("line.separator");
    StyledDocument doc = textPane.getStyledDocument();
    try {
        doc.insertString(doc.getLength(), text, style);
    } catch (BadLocationException e) {
    }
    textPane.revalidate();
    textPane.setCaretPosition(textPane.getDocument().getLength());
    scroll.revalidate();
// frame.pack();
}
Example 87
Project: bigtable-sql-master  File: VersionPane.java View source code
/**
     * Renders the content.
     */
private void init() {
    String content = getContent();
    setContentType("text/html");
    StyledDocument doc = getStyledDocument();
    SimpleAttributeSet s = new SimpleAttributeSet();
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    StyleConstants.setBold(s, true);
    try {
        doc.setParagraphAttributes(0, content.length(), s, false);
        doc.insertString(0, content, s);
        if (_showWebsite) {
            String webContent = Version.getWebSite();
            SimpleAttributeSet w = new SimpleAttributeSet();
            StyleConstants.setAlignment(w, StyleConstants.ALIGN_CENTER);
            StyleConstants.setUnderline(w, true);
            SimpleAttributeSet hrefAttr = new SimpleAttributeSet();
            hrefAttr.addAttribute(HTML.Attribute.HREF, Version.getWebSite());
            w.addAttribute(HTML.Tag.A, hrefAttr);
            doc.setParagraphAttributes(content.length(), webContent.length(), w, false);
            doc.insertString(content.length(), webContent, w);
            if (Desktop.isDesktopSupported()) {
                addMouseListener(this);
                addMouseMotionListener(this);
            }
        }
    } catch (Exception e) {
        s_log.error("init: Unexpected exception " + e.getMessage());
    }
    setOpaque(false);
}
Example 88
Project: BotLibre-master  File: TextPanel.java View source code
public void appendText(String text) {
    try {
        HTMLEditorKit kit = (HTMLEditorKit) outputTextPane.getEditorKit();
        StyledDocument document = (StyledDocument) outputTextPane.getDocument();
        kit.insertHTML((HTMLDocument) document, document.getLength(), text, 0, 0, null);
    } catch (Exception ignore) {
    }
}
Example 89
Project: cakephp3-netbeans-master  File: CakePHP3CompletionItem.java View source code
@Override
public void defaultAction(JTextComponent jtc) {
    try {
        final StyledDocument doc = (StyledDocument) jtc.getDocument();
        NbDocument.runAtomicAsUser(doc, new Runnable() {

            @Override
            public void run() {
                try {
                    String insertString;
                    if (text.startsWith(filter)) {
                        // NOI18N
                        insertString = text.replaceFirst(filter, "");
                        doc.insertString(startOffset, insertString, null);
                    } else {
                        insertString = text;
                        int removeLength = filter.length();
                        int removeStart = startOffset - removeLength;
                        if (removeStart >= 0) {
                            doc.remove(removeStart, removeLength);
                            doc.insertString(removeStart, insertString, null);
                        } else {
                            // NOI18N
                            LOGGER.log(Level.WARNING, "Invalid start position[text: {0}, filter: {1}]", new Object[] { text, filter });
                        }
                    }
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
                Completion.get().hideAll();
            }
        });
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
Example 90
Project: cayenne-master  File: TextPaneView.java View source code
@Override
protected int drawUnselectedText(Graphics graphics, int x, int y, int p0, int p1) throws BadLocationException {
    boolean lineComment = false;
    Map<Integer, Integer> comment = new HashMap<>();
    Map<Integer, Integer> commentInLine = new HashMap<>();
    StyledDocument doc = (StyledDocument) getDocument();
    String text = doc.getText(p0, p1 - p0);
    Segment segment = getLineBuffer();
    Matcher m = patternComment.matcher(doc.getText(0, doc.getLength()));
    int maxEnd = 0;
    while (m.find()) {
        comment.put(m.start(), m.end());
        if (maxEnd < m.end()) {
            maxEnd = m.end();
        }
    }
    Matcher m3 = patternCommentStart.matcher(doc.getText(0, doc.getLength()));
    while (m3.find()) {
        if (maxEnd < m3.start()) {
            comment.put(m3.start(), doc.getLength());
            break;
        }
    }
    for (Map.Entry<Integer, Integer> entry : comment.entrySet()) {
        if (p0 >= entry.getKey() && p1 <= entry.getValue()) {
            lineComment = true;
            break;
        } else if (p0 <= entry.getKey() && p1 >= entry.getValue()) {
            commentInLine.put(entry.getKey() - p0, entry.getValue() - p0);
        } else if (p0 <= entry.getKey() && p1 >= entry.getKey() && p1 < entry.getValue()) {
            commentInLine.put(entry.getKey() - p0, p1 - p0);
        } else if (p0 <= entry.getValue() && p1 >= entry.getValue() && p0 > entry.getKey()) {
            commentInLine.put(0, entry.getValue() - p0);
        }
    }
    SortedMap<Integer, Integer> startMap = new TreeMap<>();
    SortedMap<Integer, SyntaxStyle> syntaxStyleMap = new TreeMap<>();
    if (lineComment) {
        startMap.put(0, text.length());
        syntaxStyleMap.put(0, syntaxStyleComment);
    } else {
        for (Map.Entry<Integer, Integer> entryCommentInLine : commentInLine.entrySet()) {
            startMap.put(entryCommentInLine.getKey(), entryCommentInLine.getValue());
            syntaxStyleMap.put(entryCommentInLine.getKey(), syntaxStyleComment);
        }
        // Match all regexes on this snippet, store positions
        for (Map.Entry<Pattern, SyntaxStyle> entry : patternSyntaxStyle.entrySet()) {
            Matcher matcher = entry.getKey().matcher(text);
            while (matcher.find()) {
                if ((text.length() == matcher.end() || text.charAt(matcher.end()) == '\t' || text.charAt(matcher.end()) == ' ' || text.charAt(matcher.end()) == '\n') && (matcher.start() == 0 || text.charAt(matcher.start() - 1) == '\t' || text.charAt(matcher.start() - 1) == '\n' || text.charAt(matcher.start() - 1) == ' ')) {
                    boolean inComment = false;
                    for (Map.Entry<Integer, Integer> entryCommentInLine : commentInLine.entrySet()) {
                        if (matcher.start(1) >= entryCommentInLine.getKey() && matcher.end() <= entryCommentInLine.getValue()) {
                            inComment = true;
                        }
                    }
                    if (!inComment) {
                        startMap.put(matcher.start(1), matcher.end());
                        syntaxStyleMap.put(matcher.start(1), entry.getValue());
                    }
                }
            }
        }
        for (Map.Entry<Pattern, SyntaxStyle> entry : patternValue.entrySet()) {
            Matcher matcher = entry.getKey().matcher(text);
            while (matcher.find()) {
                if ((text.length() == matcher.end() || text.charAt(matcher.end()) == ' ' || text.charAt(matcher.end()) == ')' || text.charAt(matcher.end()) == '\t' || text.charAt(matcher.end()) == '\n') && (matcher.start() == 0 || text.charAt(matcher.start() - 1) == '\t' || text.charAt(matcher.start() - 1) == ' ' || text.charAt(matcher.start() - 1) == '=' || text.charAt(matcher.start() - 1) == '(')) {
                    boolean inComment = false;
                    for (Map.Entry<Integer, Integer> entryCommentInLine : commentInLine.entrySet()) {
                        if (matcher.start() >= entryCommentInLine.getKey() && matcher.end() <= entryCommentInLine.getValue()) {
                            inComment = true;
                        }
                    }
                    if (!inComment) {
                        startMap.put(matcher.start(), matcher.end());
                        syntaxStyleMap.put(matcher.start(), entry.getValue());
                    }
                }
            }
        }
    }
    // TODO: check the map for overlapping parts
    int i = 0;
    // Colour the parts
    for (Map.Entry<Integer, Integer> entry : startMap.entrySet()) {
        int start = entry.getKey();
        int end = entry.getValue();
        if (i < start) {
            graphics.setColor(SQLSyntaxConstants.DEFAULT_COLOR);
            graphics.setFont(SQLSyntaxConstants.DEFAULT_FONT);
            doc.getText(p0 + i, start - i, segment);
            x = Utilities.drawTabbedText(segment, x, y, graphics, this, i);
        }
        graphics.setFont(syntaxStyleMap.get(start).getFont());
        graphics.setColor(syntaxStyleMap.get(start).getColor());
        i = end;
        doc.getText(p0 + start, i - start, segment);
        x = Utilities.drawTabbedText(segment, x, y, graphics, this, start);
    }
    // Paint possible remaining text black
    if (i < text.length()) {
        graphics.setColor(SQLSyntaxConstants.DEFAULT_COLOR);
        graphics.setFont(SQLSyntaxConstants.DEFAULT_FONT);
        doc.getText(p0 + i, text.length() - i, segment);
        x = Utilities.drawTabbedText(segment, x, y, graphics, this, i);
    }
    return x;
}
Example 91
Project: ClothoBiofabEdition-master  File: errorgui.java View source code
public void run() {
    Document doc = textPane.getDocument();
    MutableAttributeSet maset = new SimpleAttributeSet();
    try {
        int startpos = doc.getLength();
        int tlength = text.length();
        doc.insertString(doc.getLength(), text, null);
        StyledDocument d = textPane.getStyledDocument();
        StyleConstants.setForeground(maset, Color.black);
        if (isErr) {
            StyleConstants.setForeground(maset, Color.red);
        }
        d.setCharacterAttributes(startpos, tlength, maset, false);
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
    textPane.setCaretPosition(doc.getLength() - 1);
}
Example 92
Project: eclipse-telemetry-master  File: JTextPaneAppender.java View source code
/**
	 * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
	 */
@Override
public void append(LoggingEvent event) {
    if (myTextPane == null) {
        LogLog.warn("TextPane is not initialized");
        return;
    }
    // if myTextPane == null
    String text = this.layout.format(event);
    String[] stackTrace = event.getThrowableStrRep();
    if (stackTrace != null) {
        StringBuffer sb = new StringBuffer(text);
        for (int i = 0; i < stackTrace.length; i++) {
            sb.append("    ").append(stackTrace[i]).append("\n");
        // for i
        }
        text = sb.toString();
    }
    StyledDocument myDoc = myTextPane.getStyledDocument();
    try {
        myDoc.insertString(myDoc.getLength(), text, myAttributeSet.get(event.getLevel().toString()));
        // Removes the same qty of the text added if line count > maxLines
        if (myDoc.getDefaultRootElement().getElementCount() > maxLines)
            myDoc.remove(0, text.length());
    } catch (BadLocationException badex) {
        System.err.println(badex);
    }
    myTextPane.setCaretPosition(myDoc.getLength());
}
Example 93
Project: elki-master  File: LogPane.java View source code
/**
   * Publish a log record to the logging pane.
   * 
   * @param record
   *        Log record
   * @throws Exception
   */
protected synchronized void publish(LogRecord record) throws BadLocationException {
    // choose an appropriate formatter
    final Formatter fmt;
    final Style style;
    // always format progress messages using the progress formatter.
    if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
        // format errors using the error formatter
        fmt = errformat;
        style = errStyle;
    } else if (record.getLevel().intValue() <= Level.FINE.intValue()) {
        // format debug statements using the debug formatter.
        fmt = debugformat;
        style = dbgStyle;
    } else {
        // default to the message formatter.
        fmt = msgformat;
        style = msgStyle;
    }
    // format
    final String m;
    m = fmt.format(record);
    StyledDocument doc = getStyledDocument();
    if (record instanceof ProgressLogRecord) {
        if (lastNewlinePos < doc.getLength()) {
            doc.remove(lastNewlinePos, doc.getLength() - lastNewlinePos);
        }
    } else {
        // insert a newline, if we didn't see one yet.
        if (lastNewlinePos < doc.getLength()) {
            doc.insertString(doc.getLength(), "\n", style);
            lastNewlinePos = doc.getLength();
        }
    }
    int tail = tailingNonNewline(m, 0, m.length());
    int headlen = m.length() - tail;
    if (headlen > 0) {
        String pre = m.substring(0, headlen);
        doc.insertString(doc.getLength(), pre, style);
    }
    lastNewlinePos = doc.getLength();
    if (tail > 0) {
        String post = m.substring(m.length() - tail);
        doc.insertString(lastNewlinePos, post, style);
    }
}
Example 94
Project: eurocarbdb-master  File: StyledTextCellRenderer.java View source code
private void setValue(Object value) {
    StyledDocument doc = textPane.getStyledDocument();
    textPane.setText("");
    try {
        if (value != null) {
            int last_count = 0;
            String text = (String) value;
            StringBuilder buffer = new StringBuilder(text.length());
            for (int i = 0; i < text.length(); i++) {
                if (text.charAt(i) == '_' || text.charAt(i) == '^') {
                    // flush buffer
                    if (buffer.length() > 0) {
                        doc.insertString(doc.getLength(), buffer.toString(), doc.getStyle("base"));
                        buffer = new StringBuilder(text.length());
                    }
                    // get special text
                    Style style = (text.charAt(i) == '_') ? doc.getStyle("subscript") : doc.getStyle("superscript");
                    String toadd = "";
                    if (i < (text.length() - 1)) {
                        if (text.charAt(i + 1) == '{') {
                            int ind = TextUtils.findClosedParenthesis(text, i + 2, '{', '}');
                            if (ind != -1) {
                                toadd = text.substring(i + 2, ind);
                                i = ind;
                            } else {
                                toadd = text.substring(i + 2);
                                i = text.length() - 1;
                            }
                        } else {
                            toadd = "" + text.charAt(i + 1);
                            i = i + 1;
                        }
                        doc.insertString(doc.getLength(), toadd, style);
                    }
                } else if ((buffer.length() - last_count) > MAX_LINE_SIZE && (text.charAt(i) == ',' || text.charAt(i) == ' ')) {
                    buffer.append('\n');
                    for (; text.charAt(i + 1) == ' '; i++) ;
                    last_count = buffer.length();
                } else
                    buffer.append(text.charAt(i));
            }
            // flush buffer
            if (buffer.length() > 0)
                doc.insertString(doc.getLength(), buffer.toString(), doc.getStyle("base"));
        }
    } catch (Exception e) {
        LogUtils.report(e);
    }
}
Example 95
Project: freecol-android-master  File: UnitDetailPanel.java View source code
/**
     * Builds the details panel for the UnitType with the given ID.
     *
     * @param id the ID of a UnitType
     * @param panel the detail panel to build
     */
public void buildDetail(String id, JPanel panel) {
    if (getId().equals(id) || ("colopediaAction." + PanelType.SKILLS).equals(id)) {
        return;
    }
    UnitType type = getSpecification().getUnitType(id);
    panel.setLayout(new MigLayout("wrap 4", "[]20[]40[]20[]"));
    JLabel name = localizedLabel(type.getNameKey());
    name.setFont(smallHeaderFont);
    panel.add(name, "span, align center, wrap 40");
    panel.add(localizedLabel("colopedia.unit.offensivePower"));
    panel.add(new JLabel(Integer.toString(type.getOffence())), "right");
    panel.add(localizedLabel("colopedia.unit.defensivePower"));
    panel.add(new JLabel(Integer.toString(type.getDefence())), "right");
    panel.add(localizedLabel("colopedia.unit.movement"));
    panel.add(new JLabel(String.valueOf(type.getMovement() / 3)), "right");
    if (type.canCarryGoods() || type.canCarryUnits()) {
        panel.add(localizedLabel("colopedia.unit.capacity"));
        panel.add(new JLabel(Integer.toString(type.getSpace())), "right");
    }
    Player player = getMyPlayer();
    // player can be null when using the map editor
    Europe europe = (player == null) ? null : player.getEurope();
    String price = null;
    if (europe != null && europe.getUnitPrice(type) > 0) {
        price = Integer.toString(europe.getUnitPrice(type));
    } else if (type.getPrice() > 0) {
        price = Integer.toString(type.getPrice());
    }
    if (price != null) {
        panel.add(localizedLabel("colopedia.unit.price"));
        panel.add(new JLabel(price), "right");
    }
    if (type.hasSkill()) {
        panel.add(localizedLabel("colopedia.unit.skill"));
        panel.add(new JLabel(Integer.toString(type.getSkill())), "right");
        List<BuildingType> schools = new ArrayList<BuildingType>();
        for (final BuildingType buildingType : getSpecification().getBuildingTypeList()) {
            if (buildingType.hasAbility(Ability.CAN_TEACH) && buildingType.canAdd(type)) {
                schools.add(buildingType);
            }
        }
        if (!schools.isEmpty()) {
            panel.add(localizedLabel("colopedia.unit.school"), "newline");
            int count = 0;
            for (BuildingType school : schools) {
                JButton label = getButton(school);
                if (count > 0 && count % 3 == 0) {
                    panel.add(label, "skip");
                } else {
                    panel.add(label);
                }
                count++;
            }
        }
        List<IndianNationType> nations = new ArrayList<IndianNationType>();
        for (IndianNationType nation : getSpecification().getIndianNationTypes()) {
            for (RandomChoice<UnitType> choice : nation.getSkills()) {
                if (choice.getObject() == type) {
                    nations.add(nation);
                }
            }
        }
        if (!nations.isEmpty()) {
            panel.add(localizedLabel("colopedia.unit.natives"), "newline");
            int count = 0;
            for (IndianNationType nation : nations) {
                JButton label = getButton(nation);
                if (count > 0 && count % 3 == 0) {
                    panel.add(label, "skip");
                } else {
                    panel.add(label);
                }
                count++;
            }
        }
    }
    // Requires - prerequisites to build
    if (!type.getAbilitiesRequired().isEmpty()) {
        panel.add(localizedLabel("colopedia.unit.requirements"), "newline, top");
        String key = type.getAbilitiesRequired().keySet().iterator().next();
        try {
            JTextPane textPane = getDefaultTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            appendRequiredAbilities(doc, type);
            panel.add(textPane, "span, width 70%");
        } catch (BadLocationException e) {
        }
    }
    List<Modifier> bonusList = new ArrayList<Modifier>();
    for (GoodsType goodsType : getSpecification().getGoodsTypeList()) {
        bonusList.addAll(type.getModifierSet(goodsType.getId()));
    }
    int bonusNumber = bonusList.size();
    if (bonusNumber > 0) {
        StringTemplate template = StringTemplate.template("colopedia.unit.productionBonus").addAmount("%number%", bonusNumber);
        panel.add(localizedLabel(template), "newline 20, top");
        JPanel productionPanel = new JPanel(new GridLayout(0, MODIFIERS_PER_ROW));
        productionPanel.setOpaque(false);
        for (Modifier productionBonus : bonusList) {
            GoodsType goodsType = getSpecification().getGoodsType(productionBonus.getId());
            String bonus = getModifierAsString(productionBonus);
            productionPanel.add(getGoodsButton(goodsType, bonus));
        }
        panel.add(productionPanel, "span");
    }
    if (!type.getGoodsRequired().isEmpty()) {
        panel.add(localizedLabel("colopedia.unit.goodsRequired"), "newline 20");
        AbstractGoods goods = type.getGoodsRequired().get(0);
        if (type.getGoodsRequired().size() > 1) {
            panel.add(getGoodsButton(goods.getType(), goods.getAmount()), "span, split " + type.getGoodsRequired().size());
            for (int index = 1; index < type.getGoodsRequired().size(); index++) {
                goods = type.getGoodsRequired().get(index);
                panel.add(getGoodsButton(goods.getType(), goods.getAmount()));
            }
        } else {
            panel.add(getGoodsButton(goods.getType(), goods.getAmount()));
        }
    }
    panel.add(localizedLabel("colopedia.unit.description"), "newline 20");
    panel.add(getDefaultTextArea(Messages.message(type.getDescriptionKey()), 30), "span");
}
Example 96
Project: fuelphp-netbeans-master  File: FuelPhpCompletionItem.java View source code
@Override
public void defaultAction(JTextComponent jtc) {
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        doc.remove(startOffset, removeLength);
        doc.insertString(startOffset, text, null);
        Completion.get().hideAll();
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
Example 97
Project: GenericKnimeNodes-master  File: ParameterDialog.java View source code
private void updateDocumentationSection(String description) {
    StyledDocument doc = (StyledDocument) help.getDocument();
    Style style = doc.addStyle("StyleName", null);
    StyleConstants.setFontFamily(style, "SansSerif");
    try {
        doc.remove(0, doc.getLength());
        doc.insertString(0, description, style);
    } catch (BadLocationException e) {
        LOGGER.warn("Documentation update failed.", e);
    }
}
Example 98
Project: geotoolkit-master  File: JCQLTextPane.java View source code
private void updateHightLight() {
    final StyledDocument doc = (StyledDocument) guiText.getDocument();
    final String txt = guiText.getText();
    final ParseTree tree = CQL.compile(txt);
    doc.setCharacterAttributes(0, txt.length(), styleError, true);
    syntaxHighLight(tree, doc, new AtomicInteger());
    firePropertyChange("content", null, txt);
}
Example 99
Project: gtitool-master  File: ExchangeDialog.java View source code
/**
   * Appends the given message.
   * 
   * @param message The message to append.
   * @param error Flag that indicates if the message should be a error message.
   */
protected final void appendMessage(String message, boolean error) {
    SimpleAttributeSet set = new SimpleAttributeSet();
    if (error) {
        StyleConstants.setForeground(set, Color.RED);
    } else {
        StyleConstants.setForeground(set, Color.BLACK);
    }
    //$NON-NLS-1$
    String lineBreak = System.getProperty("line.separator");
    try {
        StyledDocument styledDocument = (StyledDocument) this.gui.jGTITextPaneStatus.getDocument();
        styledDocument.insertString(styledDocument.getLength(), message + lineBreak, set);
    } catch (BadLocationException exc) {
        exc.printStackTrace();
        System.exit(1);
    }
}
Example 100
Project: jASM_16-master  File: CPUView.java View source code
@Override
public void run() {
    final StyledDocument doc = textArea.getStyledDocument();
    doc.putProperty(Document.StreamDescriptionProperty, null);
    textArea.setText(builder.toString());
    for (ITextRegion region : redRegions) {
        doc.setCharacterAttributes(region.getStartingOffset(), region.getLength(), errorStyle, true);
    }
}
Example 101
Project: KinOathKinshipArchiver-master  File: KinTypeStringInput.java View source code
public void highlightKinTypeStrings(ParserHighlight[] parserHighlight, String[] kinTypeStrings) {
    this.parserHighlight = parserHighlight;
    StyledDocument styledDocument = this.getStyledDocument();
    int lineStart = 0;
    for (int lineCounter = 0; lineCounter < parserHighlight.length; lineCounter++) {
        ParserHighlight currentHighlight = parserHighlight[lineCounter];
        //                int lineStart = styledDocument.getParagraphElement(lineCounter).getStartOffset();
        //                int lineEnd = styledDocument.getParagraphElement(lineCounter).getEndOffset();
        int lineEnd = lineStart + kinTypeStrings[lineCounter].length();
        styledDocument.setCharacterAttributes(lineStart, lineEnd, this.getStyle("Unknown"), true);
        while (currentHighlight.highlight != null) {
            int startPos = lineStart + currentHighlight.startChar;
            int charCount = lineEnd - lineStart;
            if (currentHighlight.nextHighlight.highlight != null) {
                charCount = currentHighlight.nextHighlight.startChar - currentHighlight.startChar;
            }
            if (currentHighlight.highlight != null) {
                String styleName = currentHighlight.highlight.name();
                styledDocument.setCharacterAttributes(startPos, charCount, this.getStyle(styleName), true);
            }
            currentHighlight = currentHighlight.nextHighlight;
        }
        lineStart += kinTypeStrings[lineCounter].length() + 1;
    }
}