Example usage for javax.swing.text StyledDocument getStyle

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

Introduction

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

Prototype

public Style getStyle(String nm);

Source Link

Document

Fetches a named style previously added.

Usage

From source file:StyledSample.java

public static void main(String args[]) {
    String BOLD_ITALIC = "BoldItalic";
    String GRAY_PLAIN = "Gray";
    JFrame frame = new JFrame("Simple Attributes");
    Container content = frame.getContentPane();

    StyledDocument document = new DefaultStyledDocument();

    Style style = (Style) document.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setBold(style, true);
    StyleConstants.setItalic(style, true);
    document.addStyle(BOLD_ITALIC, null);

    //    style = document.getStyle(StyleContext.DEFAULT_STYLE);
    //    StyleConstants.setBold(style, false);
    //    StyleConstants.setItalic(style, false);
    //    StyleConstants.setForeground(style, Color.lightGray);
    //    document.addStyle(GRAY_PLAIN, null);

    style = document.getStyle(BOLD_ITALIC);

    // Insert content
    try {//from   ww  w  . jav  a 2 s.  c  o m
        document.insertString(document.getLength(), "Hello Java\n", style);
    } catch (BadLocationException badLocationException) {
        System.err.println("Oops");
    }

    style = document.getStyle(GRAY_PLAIN);

    // Insert content
    try {
        document.insertString(document.getLength(), " - Good-bye Visual Basic\n", style);
    } catch (BadLocationException badLocationException) {
        System.err.println("Oops");
    }

    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);
    content.add(scrollPane, BorderLayout.CENTER);

    frame.setSize(300, 150);
    frame.setVisible(true);
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.GUIComponent.java

public JTextPane createJTextPane() {
    String newline = "\n";
    String[] description = { "PubChem XML Tool (Version: " + version + ")" + newline,
            "By: S. Canny (scanny@scripps.edu) and M. Southern (southern@scripps.edu)" + newline, "" + newline,
            "PubChem XML Tool main functions:" + newline,
            "1. Create a PubChem XML that can include Assay, Result TIDs, Xrefs, Panel, and Categorized Comments."
                    + newline,//ww  w  .  j  av a  2  s  .  co m
            "2. Extract Assay, Result TID, Xref, Panel, and Categorized Comment information from a PubChem XML."
                    + newline,
            "3. Create a report from an Excel workbook or PubChem XMLs." + newline, "" + newline,
            "Other features:" + newline,
            "1. Automatically adds reference section to description of PubChem XML or a report if placeholder is used."
                    + newline,
            "2. Checks proteins, genes, omims, and taxonomies for connections when creating PubChem XML or a report."
                    + newline,
            "3. Can retrieve on-hold and newly deposited assays from deposition system to extract or create report."
                    + newline,
            "" + newline, "\t\t\t(c) 2010, The Scripps Research Institute- Florida" };
    String[] styles = { "bold", "regular", "regular", "regular", "regular", "regular", "regular", "regular",
            "regular", "regular", "regular", "regular", "regular", "regular", "right" };

    JTextPane jtp = new JTextPane();
    StyledDocument doc = jtp.getStyledDocument();
    addStylesToDocument(doc);

    try {
        for (int ii = 0; ii < description.length; ii++)
            doc.insertString(doc.getLength(), description[ii], doc.getStyle(styles[ii]));
    } catch (BadLocationException ble) {
        log.error(ble.getMessage(), ble);
    }
    jtp.setOpaque(false);
    jtp.setEditable(false);
    jtp.setPreferredSize(new Dimension(640, 230));

    return jtp;
}

From source file:TextSamplerDemo.java

private JTextPane createTextPane() {
    String[] initString = { "This is an editable JTextPane, ", //regular
            "another ", //italic
            "styled ", //bold
            "text ", //small
            "component, ", //large
            "which supports embedded components..." + newline, //regular
            " " + newline, //button
            "...and embedded icons..." + newline, //regular
            " ", //icon
            newline + "JTextPane is a subclass of JEditorPane that "
                    + "uses a StyledEditorKit and StyledDocument, and provides "
                    + "cover methods for interacting with those objects." };

    String[] initStyles = { "regular", "italic", "bold", "small", "large", "regular", "button", "regular",
            "icon", "regular" };

    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);/*from w  ww. j a v a  2 s  .  com*/

    try {
        for (int i = 0; i < initString.length; i++) {
            doc.insertString(doc.getLength(), initString[i], doc.getStyle(initStyles[i]));
        }
    } catch (BadLocationException ble) {
        System.err.println("Couldn't insert initial text into text pane.");
    }

    return textPane;
}

From source file:de.tor.tribes.ui.wiz.ref.SupportRefillCalculationPanel.java

public void notifyStatusUpdate(String pMessage) {
    try {//  w  w w .  j  a  v  a 2s .  c  om
        StyledDocument doc = jTextPane1.getStyledDocument();
        doc.insertString(doc.getLength(),
                "(" + dateFormat.format(new Date(System.currentTimeMillis())) + ") " + pMessage + "\n",
                doc.getStyle("Info"));
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                scroll();
            }
        });
    } catch (BadLocationException ignored) {
    }
}

From source file:dylemator.DylematorUI.java

private void displayCenteredText(String text) {
    textArea.setText("");
    text = "\n\n\n" + text;
    SimpleAttributeSet attribs = new SimpleAttributeSet();
    if (sd == null)
        sd = new SettingsDialog(this, true);
    float fnt = sd.getFontSize();
    StyledDocument doc = (StyledDocument) textArea.getDocument();
    Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);//doc.addStyle("MyStyle",null);
    StyleConstants.setFontSize(style, (int) fnt);
    StyleConstants.setLineSpacing(attribs, 0.5f);
    StyleConstants.setFontFamily(style, "Segoe UI");
    StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_CENTER);
    textArea.setParagraphAttributes(attribs, true);

    try {/*  ww  w  . jav  a  2 s .  c o m*/
        doc.insertString(doc.getLength(), text, style);
        doc.setParagraphAttributes(0, doc.getLength() - 1, attribs, false);
    } catch (BadLocationException ex) {
        Logger.getLogger(DylematorUI.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:gda.gui.BatonPanel.java

private void updateMessagePanel(final UserMessage message) {
    SwingUtilities.invokeLater(new Runnable() {

        private void addMessageHeader() throws BadLocationException {
            StyledDocument doc = (StyledDocument) logPanel.getDocument();

            Date date = new Date();
            Format formatter = new SimpleDateFormat("dd MMM HH:mm:ss");
            String newMessage = "\n" + formatter.format(date) + "\t";

            newMessage += "#" + message.getSourceClientNumber();
            newMessage += " " + message.getSourceUsername() + "";

            doc.insertString(doc.getLength(), newMessage, doc.getStyle("bold"));
        }/*from   www.ja  va 2s .co m*/

        private void addMessageBody() throws BadLocationException {
            StyledDocument doc = (StyledDocument) logPanel.getDocument();
            String newMessage = "\n    ";
            newMessage += message.getMessage();
            doc.insertString(doc.getLength(), newMessage, doc.getStyle("regular"));
        }

        @Override
        public void run() {
            try {
                addMessageHeader();
                addMessageBody();
                // scroll down to display new message
                getLogPanel().getCaret().setDot(getLogPanel().getText().length());
                saveLog(logPanel.getStyledDocument());
            } catch (BadLocationException e) {
                //
            }
        }
    });
}

From source file:org.drugis.addis.gui.wizard.AddStudyWizard.java

private static JComponent buildTip(String tip) {
    JTextPane area = new JTextPane();
    StyledDocument doc = area.getStyledDocument();
    addStylesToDoc(doc);/*from  ww  w. java 2 s. c  o m*/

    area.setBackground(new Color(255, 180, 180));

    try {
        doc.insertString(0, "x", doc.getStyle("tip"));
        doc.insertString(doc.getLength(), " Tip: \n", doc.getStyle("bold"));
        doc.insertString(doc.getLength(), tip, doc.getStyle("regular"));
    } catch (BadLocationException e) {
        e.printStackTrace();
    }

    area.setEditable(false);

    JScrollPane pane = new JScrollPane(area);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    pane.setPreferredSize(TextComponentFactory.textPaneDimension(area, 270, 70));

    pane.setWheelScrollingEnabled(true);
    pane.getVerticalScrollBar().setValue(0);

    return pane;
}

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

/** 
 * Adds the text to the debug pane.//w  w  w .  j  a  v a  2  s. 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.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 a  v  a  2  s. c  o  m
 */
@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 {// w w  w .j  ava 2s .  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);
        }
    }
}