Example usage for javax.swing.text StyledDocument insertString

List of usage examples for javax.swing.text StyledDocument insertString

Introduction

In this page you can find the example usage for javax.swing.text StyledDocument insertString.

Prototype

public void insertString(int offset, String str, AttributeSet a) throws BadLocationException;

Source Link

Document

Inserts a string of content.

Usage

From source file:org.openmicroscopy.shoola.agents.fsimporter.view.ImporterUI.java

/** 
 * Adds the text to the debug pane./*from  ww w  .j a  v  a 2s  .  c  o  m*/
 * 
 * @param text The text to display.
 */
void appendDebugText(String text) {
    if (debugTextPane == null)
        return;
    StyledDocument doc = (StyledDocument) debugTextPane.getDocument();
    try {
        doc.insertString(doc.getLength(), text, doc.getStyle(STYLE));
        if (doc.getLength() > MAX_CHAR)
            doc.remove(0, doc.getLength() - MAX_CHAR);
    } catch (Exception e) {
        //ignore
    }
}

From source file:org.openmicroscopy.shoola.util.ui.MessengerDialog.java

/**
 * Builds the UI component displaying the exception.
 * /*w w  w.j a v a  2s  .c om*/
 * @return See above.
 */
private JTextPane buildExceptionArea() {
    JTextPane pane = UIUtilities.buildExceptionArea();
    StyledDocument document = pane.getStyledDocument();
    Style style = pane.getLogicalStyle();
    //Get the full debug text
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    exception.printStackTrace(pw);
    try {
        document.insertString(document.getLength(), sw.toString(), style);
    } catch (BadLocationException e) {
    }

    return pane;
}

From source file:org.openmicroscopy.shoola.util.ui.UIUtilities.java

/**
 * Formats the text and displays it in a {@link JTextPane}.
 * //from  ww w . j a  v  a  2 s.  c o  m
 * @param text          The text to display.
 * @param foreground   The foreground color.
 * @return See above.
 */
public static JTextPane buildTextPane(String text, Color foreground) {
    if (text == null)
        text = "";
    StyleContext context = new StyleContext();
    StyledDocument document = new DefaultStyledDocument(context);

    Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT);
    if (foreground != null)
        StyleConstants.setForeground(style, foreground);
    try {
        document.insertString(document.getLength(), text, style);
    } catch (BadLocationException e) {
    }

    JTextPane textPane = new JTextPane(document);
    textPane.setOpaque(false);
    textPane.setEditable(false);
    textPane.setFocusable(false);
    return textPane;
}

From source file:org.quackbot.gui.GUIConsoleAppender.java

/**
 * Used by Log4j to write something from the LoggingEvent. This simply points to
 * WriteOutput which writes to the the GUI or to the console
 * @param event//w w  w .j  av  a  2s.  c om
 */
@Override
public void append(final ILoggingEvent event) {
    if (!inited)
        synchronized (initMessageQueue) {
            if (!inited) {
                initMessageQueue.add(event);
                return;
            }
        }

    //Grab bot info off of MDC
    final String botId = MDC.get("pircbotx.id");
    final String botServer = MDC.get("pircbotx.server");
    final String botPort = MDC.get("pircbotx.port");

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                //Figure out where this is going
                JTextPane textPane = (StringUtils.isBlank(botId)) ? gui.CerrorLog : gui.BerrorLog;
                JScrollPane scrollPane = (StringUtils.isBlank(botId)) ? gui.CerrorScroll : gui.BerrorScroll;

                //Configure stle
                StyledDocument doc = textPane.getStyledDocument();
                Style msgStyle = event.getLevel().isGreaterOrEqual(Level.WARN) ? doc.getStyle("Error")
                        : doc.getStyle("Normal");

                doc.insertString(doc.getLength(), "\n", doc.getStyle("Normal"));
                int prevLength = doc.getLength();
                doc.insertString(doc.getLength(), "[" + dateFormatter.format(event.getTimeStamp()) + "] ",
                        doc.getStyle("Normal")); //time
                //doc.insertString(doc.getLength(), "["+event.getThreadName()+"] ", doc.getStyle("Thread")); //thread name
                doc.insertString(doc.getLength(), event.getLevel().toString() + " ", doc.getStyle("Level")); //Logging level
                doc.insertString(doc.getLength(), event.getLoggerName() + " ", doc.getStyle("Class"));
                if (StringUtils.isNotBlank(botId)) {
                    String port = !botPort.equals("6667") ? ":" + botPort : "";
                    doc.insertString(doc.getLength(), "<" + botId + ":" + botServer + port + "> ",
                            doc.getStyle("Server"));
                }
                doc.insertString(doc.getLength(), messageLayout.doLayout(event).trim(), msgStyle);

                //Only autoscroll if the scrollbar is at the bottom
                //JScrollBar scrollBar = scroll.getVerticalScrollBar();
                //if (scrollBar.getVisibleAmount() != scrollBar.getMaximum() && scrollBar.getValue() + scrollBar.getVisibleAmount() == scrollBar.getMaximum())
                textPane.setCaretPosition(prevLength);
            } catch (Exception e) {
                addError("Exception encountered when logging", e);
            }
        }
    });
}

From source file:org.smart.migrate.ui.ImportThread.java

@Override
public void log(String level, String msg) {
    if (logger != null) {
        StyledDocument doc = logger.getStyledDocument();
        try {//from  w ww . j  a v a2 s .  c o m
            doc.insertString(doc.getLength(), new SimpleDateFormat("MM-dd hh:mm:ss ").format(new Date()),
                    doc.getStyle("gray"));
            doc.insertString(doc.getLength(), msg + "\n", doc.getStyle(level.toLowerCase()));
            logger.setCaretPosition(logger.getDocument().getLength());
            //logger.append(   + ", level:" + level+", message: " + msg+"\n");
        } catch (BadLocationException ex) {
            Logger.getLogger(ImportThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:pl.otros.logview.gui.MessageDetailListener.java

public void updateInfo() {
    Collection<MessageFormatter> formatters = formattersContainer.getElements();
    Collection<MessageColorizer> colorizers = colorizersContainer.getElements();
    int row = table.getSelectedRow();
    if (row >= 0 && row < table.getRowCount()) {
        logDetailTextArea.setText("");
        int rowConverted = table.convertRowIndexToModel(row);
        LogData ld = dataTableModel.getLogData(rowConverted);
        StyledDocument document = logDetailTextArea.getStyledDocument();
        synchronized (document) {
            try {
                document.remove(0, document.getLength());
                String s1 = "Date:    " + dateFormat.format(ld.getDate()) + "\n";
                document.insertString(0, s1, mainStyle);
                s1 = "Class:   " + ld.getClazz() + "\n";
                document.insertString(document.getLength(), s1, classMethodStyle);
                s1 = "Method:  " + ld.getMethod() + "\n";
                document.insertString(document.getLength(), s1, classMethodStyle);
                s1 = "Level:   ";
                document.insertString(document.getLength(), s1, classMethodStyle);
                Icon levelIcon = LevelRenderer.getIconByLevel(ld.getLevel());
                if (levelIcon != null) {
                    logDetailTextArea.insertIcon(levelIcon);
                }//  w ww .j  av  a 2 s  .  co m
                s1 = " " + ld.getLevel().getName() + "\n";
                document.insertString(document.getLength(), s1, classMethodStyle);
                s1 = "Message: ";
                document.insertString(document.getLength(), s1, mainStyle);
                int beforeMessage = document.getLength();
                s1 = ld.getMessage();
                if (s1.length() > maximumMessageSize) {
                    int removedCharsSize = s1.length() - maximumMessageSize;
                    s1 = StringUtils.left(s1, maximumMessageSize)
                            + String.format("%n...%n...(+%,d chars)", removedCharsSize);
                }

                for (MessageFormatter messageFormatter : formatters) {
                    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                    try {
                        Thread.currentThread()
                                .setContextClassLoader(messageFormatter.getClass().getClassLoader());
                        if (messageFormatter.formattingNeeded(s1)) {
                            s1 = messageFormatter.format(s1);
                        }
                    } catch (Throwable e) {
                        LOGGER.severe(String.format("Error occured when using message formatter %s: %s",
                                messageFormatter.getName(), e.getMessage()));
                        LOGGER.fine(String.format(
                                "Error occured when using message formatter %s with message\"%s\"",
                                messageFormatter.getName(), s1));
                    } finally {
                        Thread.currentThread().setContextClassLoader(contextClassLoader);
                    }

                }
                document.insertString(document.getLength(), s1, mainStyle);
                searchResultMessageColorizer = null;
                for (MessageColorizer messageColorizer : colorizers) {
                    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                    try {
                        Thread.currentThread()
                                .setContextClassLoader(messageColorizer.getClass().getClassLoader());
                        if (messageColorizer.colorizingNeeded(s1)) {
                            messageColorizer.colorize(document, beforeMessage,
                                    document.getLength() - beforeMessage);
                        }
                    } catch (Throwable e) {
                        LOGGER.severe(String.format("Error occured when using message colorizer %s: %s",
                                messageColorizer.getName(), e.getMessage()));
                        LOGGER.fine(String.format(
                                "Error occured when using message colorizer %s with message\"%s\"",
                                messageColorizer.getName(), s1));
                    } finally {
                        Thread.currentThread().setContextClassLoader(contextClassLoader);
                    }

                    if (messageColorizer.getPluginableId().equals(SearchResultColorizer.class.getName())) {
                        searchResultMessageColorizer = messageColorizer;
                    }

                }
                if (searchResultMessageColorizer != null && searchResultMessageColorizer.colorizingNeeded(s1)) {
                    searchResultMessageColorizer.colorize(document, beforeMessage,
                            document.getLength() - beforeMessage);
                }
                document.insertString(document.getLength(), "\n", mainStyle);
                if (ld.getProperties() != null && ld.getProperties().size() > 0) {
                    document.insertString(document.getLength(), "\nProperties:\n", noteStyle);
                    String prop = Joiner.on("\n").withKeyValueSeparator("=").join(ld.getProperties());
                    document.insertString(document.getLength(), prop, noteStyle);
                    document.insertString(document.getLength(), "\n", noteStyle);
                }
                Note note = dataTableModel.getNote(rowConverted);
                if (note != null && note.getNote() != null && note.getNote().length() > 0) {
                    s1 = "\nNote: " + note.getNote();
                    document.insertString(document.getLength(), s1, noteStyle);
                }
            } catch (BadLocationException e) {
                LOGGER.warning("Cant set message details: " + e.getMessage());
            }
        }
    } else {
        StyledDocument document = logDetailTextArea.getStyledDocument();
        synchronized (document) {
            try {
                document.remove(0, document.getLength());
                document.insertString(0, "No event selected", mainStyle);
            } catch (BadLocationException e) {
                LOGGER.warning("Cant set message details: " + e.getMessage());
            }
        }
    }
    logDetailTextArea.setCaretPosition(0);
}

From source file:uk.ac.kcl.texthunter.core.AnnotationEditor.java

private void updateProjectSummary() {
    try {// w  ww.j  a va  2s  . c o m
        projectXML.updateProjectSummary(con, targetTableName);
    } catch (java.sql.SQLException ex) {
        updateProjectStatus("Annotation table not ready");
    }
    StyledDocument doc;
    doc = projectSummaryTextPane.getStyledDocument();
    SimpleAttributeSet newString = new SimpleAttributeSet();
    StyleConstants.setForeground(newString, Color.BLACK);
    StyleConstants.setBold(newString, true);

    StringBuilder newText = new StringBuilder("\n");
    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    Date date = new Date();

    newText.append("------ results updated on ").append(dateFormat.format(date)).append(" ------\n\n");
    newText.append("current project annotations:\n");
    newText = newText.append("Gold Standard Positive Annotations = ").append(projectXML.getGsPos())
            .append("\n");
    newText = newText.append("Gold Standard Negative Annotations = ").append(projectXML.getGsneg())
            .append("\n");
    newText = newText.append("Gold Standard Unknown Annotations = ").append(projectXML.getGsunk()).append("\n");
    newText = newText.append("Gold Standard Form Annotations = ").append(projectXML.getGsform()).append("\n");
    newText = newText.append("Seed positive Annotations = ").append(projectXML.getSeedpos()).append("\n");
    newText = newText.append("Seed Negative Annotations = ").append(projectXML.getSeedneg()).append("\n");
    newText = newText.append("Seed Unknown Annotations = ").append(projectXML.getSeedunk()).append("\n");
    newText = newText.append("Seed Form Annotations = ").append(projectXML.getSeedform()).append("\n");
    newText = newText.append("AL Positive Annotations = ").append(projectXML.getAlpos()).append("\n");
    newText = newText.append("AL Negative Annotations = ").append(projectXML.getAlneg()).append("\n");
    newText = newText.append("AL Form Annotations = ").append(projectXML.getAlform()).append("\n");
    newText = newText.append("AL Unknown Annotations = ").append(projectXML.getAlunk()).append("\n\n");

    newText = newText.append("Last Pipeline run results:\n");
    newText = newText.append("P = ").append(projectXML.getPrecision()).append("\n");
    newText = newText.append("R = ").append(projectXML.getRecall()).append("\n");
    newText = newText.append("F1 = ").append(projectXML.getF1()).append("\n");

    try {
        doc.insertString(doc.getLength(), "\n" + newText, newString);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:uk.ac.kcl.texthunter.core.AnnotationEditor.java

private void updateInfoTextPane(String newText) {
    StyledDocument doc;
    doc = infoTextPane.getStyledDocument();

    //  Define a keyword attribute

    SimpleAttributeSet newString = new SimpleAttributeSet();
    StyleConstants.setForeground(newString, Color.RED);
    StyleConstants.setBold(newString, true);

    SimpleAttributeSet oldString = new SimpleAttributeSet();
    StyleConstants.setForeground(oldString, Color.BLACK);
    StyleConstants.setBold(oldString, false);

    //  Add some text

    try {/*from  w ww .j a  v  a2 s.  c o m*/
        doc.setCharacterAttributes(0, doc.getLength(), oldString, true);
        doc.insertString(doc.getLength(), "\n" + newText, newString);
    } catch (Exception e) {
        System.out.println(e);
    }
}