Java Code Examples for javax.swing.text.Style

The following examples show how to use javax.swing.text.Style. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Sets the customization panel.
 *
 * @param typeName the new customization panel
 */
private void setCustomizationPanel(String typeName) {
  this.currentTypeName = typeName;
  Style defaultAnnotStyle = this.styleMap.get(CAS.TYPE_NAME_ANNOTATION);
  Style style = this.styleMap.get(typeName);
  if (style == null) {
    style = defaultAnnotStyle;
  }
  // Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(
  // StyleContext.DEFAULT_STYLE);
  setCurrentStyle(style);
  this.fgColor = StyleConstants.getForeground(this.currentStyle);
  this.bgColor = StyleConstants.getBackground(this.currentStyle);
  this.fgIcon.setColor(this.fgColor);
  this.bgIcon.setColor(this.bgColor);
  setTextPane();
  enableButtons(false);
  this.repaint();
}
 
Example 2
Source Project: binnavi   Source File: BaseTypeTableCellRenderer.java    License: Apache License 2.0 6 votes vote down vote up
private static void renderAtomic(
    final TypeInstance instance, final StyledDocument document, final boolean renderData) {
  final Style atomicStyle = createDeclarationStyle(document);
  try {
    document.remove(0, document.getLength());
    final BaseType baseType = instance.getBaseType();
    appendString(document, baseType.getName(), atomicStyle);
    if (renderData) {
      appendString(document,
          renderInstanceData(baseType, instance.getAddress().getOffset(), instance.getSection()),
          createDataStyle(document));
    }
  } catch (final BadLocationException exception) {
    CUtilityFunctions.logException(exception);
  }
}
 
Example 3
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private int getOtherToken(String content, int startOffset, int endOffset) {
  int endOfToken = startOffset + 1;
  while (endOfToken <= endOffset) {
    if (isDelimiter(content.substring(endOfToken, endOfToken + 1))) {
      break;
    }
    endOfToken++;
  }
  String token = content.substring(startOffset, endOfToken);
  Style s = getStyle(token);
  // if (keywords.containsKey(token)) {
  //  setCharacterAttributes(startOffset, endOfToken - startOffset, keywords.get(token), false);
  if (Objects.nonNull(s)) {
    setCharacterAttributes(startOffset, endOfToken - startOffset, s, false);
  }
  return endOfToken + 1;
}
 
Example 4
Source Project: uima-uimaj   Source File: MainFrame.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Save color preferences.
 *
 * @param file the file
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void saveColorPreferences(File file) throws IOException {
  Properties prefs1 = new Properties();
  Iterator<String> it = this.styleMap.keySet().iterator();
  String type;
  Style style;
  Color fg, bg;
  while (it.hasNext()) {
    type = it.next();
    style = this.styleMap.get(type);
    fg = StyleConstants.getForeground(style);
    bg = StyleConstants.getBackground(style);
    prefs1.setProperty(type, Integer.toString(fg.getRGB()) + "+" + Integer.toString(bg.getRGB()));
  }
  FileOutputStream out = new FileOutputStream(file);
  prefs1.store(out, "Color preferences for annotation viewer.");
}
 
Example 5
Source Project: WorldGrower   Source File: JTextPaneUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void appendIconAndText(JTextPane textPane, Image image, String message) {
	StyledDocument document = (StyledDocument)textPane.getDocument();
	image = StatusMessageImageConverter.convertImage(image);
	
       try {
		JLabel jl  = JLabelFactory.createJLabel("<html>" + message + "</html>", image);
		jl.setHorizontalAlignment(SwingConstants.LEFT);

		String styleName = "style"+message;
		Style textStyle = document.addStyle(styleName, null);
	    StyleConstants.setComponent(textStyle, jl);

	    document.insertString(document.getLength(), " ", document.getStyle(styleName));
	} catch (BadLocationException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 6
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new GridLayout(3, 1));

  JTextPane label1 = new JTextPane();
  // MutableAttributeSet attr = new SimpleAttributeSet();
  Style attr = label1.getStyle(StyleContext.DEFAULT_STYLE);
  StyleConstants.setLineSpacing(attr, -.2f);
  label1.setParagraphAttributes(attr, true);
  label1.setText("JTextPane\n" + DUMMY_TEXT);
  // [XP Style Icons - Download](https://xp-style-icons.en.softonic.com/)
  ImageIcon icon = new ImageIcon(getClass().getResource("wi0124-32.png"));
  add(makeLeftIcon(label1, icon));

  JTextArea label2 = new JTextArea("JTextArea\n" + DUMMY_TEXT);
  add(makeLeftIcon(label2, icon));

  JLabel label3 = new JLabel("<html>JLabel+html<br>" + DUMMY_TEXT);
  label3.setIcon(icon);
  add(label3);

  setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 7
Source Project: netbeans   Source File: ModelItem.java    License: Apache License 2.0 6 votes vote down vote up
private void printHeaders(JTextPane pane, JSONObject headers,
        StyledDocument doc, Style boldStyle, Style defaultStyle) throws BadLocationException {

    assert headers != null;
    Set keys = new TreeSet(new Comparator<Object>() {
        @Override
        public int compare(Object o1, Object o2) {
            return ((String)o1).compareToIgnoreCase((String)o2);
        }

    });
    keys.addAll(headers.keySet());
    for (Object oo : keys) {
        String key = (String)oo;
        doc.insertString(doc.getLength(), key+": ", boldStyle);
        String value = (String)headers.get(key);
        doc.insertString(doc.getLength(), value+"\n", defaultStyle);
    }
}
 
Example 8
Source Project: consulo   Source File: Browser.java    License: Apache License 2.0 6 votes vote down vote up
private void setupStyle() {
  Document document = myHTMLViewer.getDocument();
  if (!(document instanceof StyledDocument)) {
    return;
  }

  StyledDocument styledDocument = (StyledDocument)document;

  EditorColorsManager colorsManager = EditorColorsManager.getInstance();
  EditorColorsScheme scheme = colorsManager.getGlobalScheme();

  Style style = styledDocument.addStyle("active", null);
  StyleConstants.setFontFamily(style, scheme.getEditorFontName());
  StyleConstants.setFontSize(style, scheme.getEditorFontSize());
  styledDocument.setCharacterAttributes(0, document.getLength(), style, false);
}
 
Example 9
static void addParagraph(Paragraph p) {
    try {
        Style s = null;
        for (int i = 0; i < p.data.length; i++) {
            AttributedContent run = p.data[i];
            s = contentAttributes.get(run.attr);
            doc.insertString(doc.getLength(), run.content, s);
        }

        Style ls = styles.getStyle(p.logical);
        doc.setLogicalStyle(doc.getLength() - 1, ls);
        doc.insertString(doc.getLength(), "\n", null);
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source Project: netbeans   Source File: VCSHyperlinkSupport.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void insertString(StyledDocument sd, Style style) throws BadLocationException {
    if(style == null) {
        style = authorStyle;
    }
    sd.insertString(sd.getLength(), author, style);

    String iconStyleName = AUTHOR_ICON_STYLE + author;
    Style iconStyle = sd.getStyle(iconStyleName);
    if(iconStyle == null) {
        iconStyle = sd.addStyle(iconStyleName, null);
        StyleConstants.setIcon(iconStyle, kenaiUser.getIcon());
    }
    sd.insertString(sd.getLength(), " ", style);
    sd.insertString(sd.getLength(), " ", iconStyle);
}
 
Example 11
Source Project: otroslogviewer   Source File: StackTraceColorizer.java    License: Apache License 2.0 6 votes vote down vote up
protected void initStyles() {
  styleContext = new StyleContext();
  Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
  StyleConstants.setFontFamily(defaultStyle, "courier");
  styleStackTrace = styleContext.addStyle("stackTrace", defaultStyle);

  StyleConstants.setBackground(styleStackTrace, theme.getColor(ThemeKey.LOG_DETAILS_STACKTRACE_BACKGROUND));
  StyleConstants.setForeground(styleStackTrace, theme.getColor(ThemeKey.LOG_DETAILS_STACKTRACE_FOREGROUND));
  stylePackage = styleContext.addStyle("stylePackage", styleStackTrace);
  styleClass = styleContext.addStyle("styleClass", stylePackage);
  StyleConstants.setForeground(styleClass, theme.getColor(ThemeKey.LOG_DETAILS_STACKTRACE_CLASS));
  StyleConstants.setBold(styleClass, true);
  styleMethod = styleContext.addStyle("styleMethod", styleStackTrace);
  StyleConstants.setForeground(styleMethod, theme.getColor(ThemeKey.LOG_DETAILS_STACKTRACE_METHOD));
  StyleConstants.setItalic(styleMethod, true);
  StyleConstants.setBold(styleMethod, true);
  styleFile = styleContext.addStyle("styleFile", styleStackTrace);
  StyleConstants.setForeground(styleFile, theme.getColor(ThemeKey.LOG_DETAILS_STACKTRACE_FLE));
  StyleConstants.setUnderline(styleFile, true);

  styleCodeComment = styleContext.addStyle("styleCodeComment", defaultStyle);
  StyleConstants.setForeground(styleCodeComment, theme.getColor(ThemeKey.LOG_DETAILS_STACKTRACE_COMMENT));
  StyleConstants.setItalic(styleCodeComment, true);
}
 
Example 12
Source Project: gate-core   Source File: LogArea.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Try and recover from a BadLocationException thrown when inserting a string
 * into the log area. This method must only be called on the AWT event
 * handling thread.
 */
private void handleBadLocationException(BadLocationException e,
    String textToInsert, Style style) {
  originalErr.println("BadLocationException encountered when writing to "
      + "the log area: " + e);
  originalErr.println("trying to recover...");

  Document newDocument = new DefaultStyledDocument();
  try {
    StringBuilder sb = new StringBuilder();
    sb.append("An error occurred when trying to write a message to the log area.  The log\n");
    sb.append("has been cleared to try and recover from this problem.\n\n");
    sb.append(textToInsert);

    newDocument.insertString(0, sb.toString(), style);
  } catch(BadLocationException e2) {
    // oh dear, all bets are off now...
    e2.printStackTrace(originalErr);
    return;
  }
  // replace the log area's document with the new one
  setDocument(newDocument);
}
 
Example 13
static void addParagraph(Paragraph p) {
    try {
        Style s = null;
        for (int i = 0; i < p.data.length; i++) {
            AttributedContent run = p.data[i];
            s = contentAttributes.get(run.attr);
            doc.insertString(doc.getLength(), run.content, s);
        }

        Style ls = styles.getStyle(p.logical);
        doc.setLogicalStyle(doc.getLength() - 1, ls);
        doc.insertString(doc.getLength(), "\n", null);
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source Project: binnavi   Source File: BaseTypeTableCellRenderer.java    License: Apache License 2.0 6 votes vote down vote up
private static void renderArray(
    final TypeInstance instance, final StyledDocument document, final boolean renderData) {
  final Style arrayStyle = createDeclarationStyle(document);
  try {
    document.remove(0, document.getLength());
    final BaseType baseType = instance.getBaseType();
    appendString(document, baseType.getName(), arrayStyle);
    if (renderData) {
      appendString(document,
          renderInstanceData(baseType, instance.getAddress().getOffset(), instance.getSection()),
          createDataStyle(document));
    }
  } catch (final BadLocationException exception) {
    CUtilityFunctions.logException(exception);
  }
}
 
Example 15
Source Project: otroslogviewer   Source File: MessageColorizerEditor.java    License: Apache License 2.0 6 votes vote down vote up
private void refreshView() {
  LOGGER.info("refreshing view");
  Style defaultStyle = textPane.getStyle(StyleContext.DEFAULT_STYLE);
  String text = textPane.getText();
  textPane.getStyledDocument().setCharacterAttributes(0, text.length(), defaultStyle, true);
  try {
    PropertyPatternMessageColorizer propertyPatternMessageColorize = createMessageColorizer();
    if (propertyPatternMessageColorize.colorizingNeeded(text)) {
      Collection<MessageFragmentStyle> colorize = propertyPatternMessageColorize.colorize(text);
      for (MessageFragmentStyle mfs : colorize) {
        textPane.getStyledDocument().setCharacterAttributes(mfs.getOffset(), mfs.getLength(), mfs.getStyle(), mfs.isReplace());
      }
    }
  } catch (Exception e) {
    LOGGER.error(String.format("Can't init PropertyPatternMessageColorizer:%s", e.getMessage()));
    statusObserver.updateStatus(String.format("Error: %s", e.getMessage()), StatusObserver.LEVEL_ERROR);
  }

}
 
Example 16
Source Project: mzmine3   Source File: ResultsTextPane.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void appendText(String text, Style style) {
  StyledDocument doc = getStyledDocument();
  try {
    doc.insertString(doc.getLength(), text + "\n", style);
  } catch (BadLocationException e) {
    e.printStackTrace();
  }
}
 
Example 17
Source Project: mzmine3   Source File: ResultsTextPane.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void appendColoredText(String text, Color color) {
  StyledDocument doc = getStyledDocument();

  Style style = addStyle("Color Style", null);
  StyleConstants.setForeground(style, color);
  try {
    doc.insertString(doc.getLength(), text, style);
  } catch (BadLocationException e) {
    e.printStackTrace();
  }
}
 
Example 18
Source Project: gcs   Source File: MarkdownDocument.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private Style createBulletStyle(Font font) {
    Style style = addStyle("bullet", null);
    style.addAttribute(StyleConstants.FontFamily, font.getFamily());
    style.addAttribute(StyleConstants.FontSize, Integer.valueOf(font.getSize()));
    int indent = TextDrawing.getSimpleWidth(font, "• ");
    style.addAttribute(StyleConstants.FirstLineIndent, Float.valueOf(-indent));
    style.addAttribute(StyleConstants.LeftIndent, Float.valueOf(indent));
    return style;
}
 
Example 19
Source Project: dragonwell8_jdk   Source File: bug8016833.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testSuperScript() {
    System.out.println("testSuperScript()");
    bug8016833 b = new bug8016833() {
        @Override
        void setNormalStyle(Style style) {
            StyleConstants.setSuperscript(style, true);
        }
    };
    b.testUnderline();
    b.testStrikthrough();
}
 
Example 20
Source Project: dragonwell8_jdk   Source File: bug8016833.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testSubScript() {
    System.out.println("testSubScript()");
    bug8016833 b = new bug8016833() {
        @Override
        void setNormalStyle(Style style) {
            StyleConstants.setSubscript(style, true);
        }
    };
    b.testUnderline();
    b.testStrikthrough();
}
 
Example 21
@Override
protected void refreshInstructions(FunctionEditor source, boolean editing, int selectedColumn) {
  StyledDocument doc = instructions.getStyledDocument();
  Style style = doc.getStyle("blue");                                                //$NON-NLS-1$
  String s = TrackerRes.getString("ParticleDataTrackFunctionPanel.Instructions.General"); //$NON-NLS-1$
  if(!editing && hasInvalidExpressions()) {                            // error condition
    s = ToolsRes.getString("FunctionPanel.Instructions.BadCell");           //$NON-NLS-1$
    style = doc.getStyle("red");                                            //$NON-NLS-1$
  }
  instructions.setText(s);
  int len = instructions.getText().length();
  doc.setCharacterAttributes(0, len, style, false);
  revalidate();
}
 
Example 22
Source Project: TencentKona-8   Source File: bug8016833.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testSuperScript() {
    System.out.println("testSuperScript()");
    bug8016833 b = new bug8016833() {
        @Override
        void setNormalStyle(Style style) {
            StyleConstants.setSuperscript(style, true);
        }
    };
    b.testUnderline();
    b.testStrikthrough();
}
 
Example 23
Source Project: TencentKona-8   Source File: bug8016833.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testNormalScript() {
    System.out.println("testNormalScript()");
    bug8016833 b = new bug8016833() {
        @Override
        void setNormalStyle(Style style) {
        }
    };
    b.testUnderline();
    b.testStrikthrough();
}
 
Example 24
Source Project: openjdk-8   Source File: bug8016833.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testSubScript() {
    System.out.println("testSubScript()");
    bug8016833 b = new bug8016833() {
        @Override
        void setNormalStyle(Style style) {
            StyleConstants.setSubscript(style, true);
        }
    };
    b.testUnderline();
    b.testStrikthrough();
}
 
Example 25
Source Project: FancyBing   Source File: GuiUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void addStyle(JTextPane pane, String name, Color foreground,
                            Color background)
{
    StyledDocument doc = pane.getStyledDocument();
    StyleContext context = StyleContext.getDefaultStyleContext();
    Style defaultStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
    Style style = doc.addStyle(name, defaultStyle);
    StyleConstants.setForeground(style, foreground);
    StyleConstants.setBackground(style, background);
}
 
Example 26
Source Project: otroslogviewer   Source File: MessageColorizerUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Apply styles on StyledDocument using regular expression
 *
 * @param style
 *          style to apply
 * @param text
 *          text to be tested by regular expression, fragment from document
 * @param regex
 *          regular expression
 * @param group
 *          group to apply
 */
public static Collection<MessageFragmentStyle> colorizeRegex(Style style, String text, Pattern regex, int group) {
  ArrayList<MessageFragmentStyle> list = new ArrayList<>();
  Matcher matcher = regex.matcher(text);
  while (matcher.find()) {
    int start = matcher.start(group);
    int end = matcher.end(group);
    if (end - start > 0) {
      MessageFragmentStyle messageFragmentStyle = new MessageFragmentStyle(start, end - start, style, false);
      list.add(messageFragmentStyle);
    }
  }
  return list;
}
 
Example 27
Source Project: wpcleaner   Source File: MWPaneFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param doc Document.
 * @param analysis Page analysis.
 * @param link Link.
 * @return Style depending on the status of the link.
 */
private Style getInternalLinkStyle(
    StyledDocument doc,
    PageAnalysis analysis,
    PageElementInternalLink link) {
  Style style = null;

  if ((analysis != null) &&
      (analysis.getPage() != null) &&
      (analysis.getPage().getLinks() != null)) {

    // Find link target
    Page target = null;
    for (Page tmpPage : analysis.getPage().getLinks()) {
      if (Page.areSameTitle(tmpPage.getTitle(), link.getLink())) {
        target = tmpPage;
      }
    }

    // Specific styles
    if (target != null) {
      if (target.getRedirects().isRedirect()) {
        style = doc.getStyle(ConfigurationValueStyle.INTERNAL_LINK_DEFAULT_REDIRECT.getName());
      } else if (Boolean.FALSE.equals(target.isExisting())) {
        style = doc.getStyle(ConfigurationValueStyle.INTERNAL_LINK_DEFAULT_MISSING.getName());
      }
    }
  }

  // Apply default style for internal links
  if (style == null) {
    style = doc.getStyle(ConfigurationValueStyle.INTERNAL_LINK.getName());
  }

  return style;
}
 
Example 28
Source Project: aion-germany   Source File: ViewPane.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void addStyledText(String text, String style, boolean index) {
	Style s = _hexStyledDoc.getStyle(style);
	if (s == null) {
		PacketSamurai.getUserInterface().log("WARNING: Missing style for partType: " + style);
		style = "base";
	}

	try {
		_hexStyledDoc.insertString(_hexStyledDoc.getLength(), text, _hexStyledDoc.getStyle(style));
	}
	catch (BadLocationException e) {
		e.printStackTrace();
	}
}
 
Example 29
Source Project: aion-germany   Source File: ViewPane.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void highlightSelectedPart(DataPartNode node) {
	Style style = _hexStyledDoc.getStyle("selected");
	StyleConstants.setForeground(style, Color.WHITE);
	
	int offset = node.getOffset();
	offset += offset/(16*3)*19;
	try {
		String text = _hexStyledDoc.getText(offset, node.getLength());
		_hexStyledDoc.replace(offset, node.getLength(), text, style);
		_hexDumpArea.setCaretPosition(offset);
	}
	catch (BadLocationException e) {
		e.printStackTrace();
	}
}
 
Example 30
Source Project: openjdk-jdk8u   Source File: bug8016833.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testSuperScript() {
    System.out.println("testSuperScript()");
    bug8016833 b = new bug8016833() {
        @Override
        void setNormalStyle(Style style) {
            StyleConstants.setSuperscript(style, true);
        }
    };
    b.testUnderline();
    b.testStrikthrough();
}