javax.swing.text.StyleContext Java Examples

The following examples show how to use javax.swing.text.StyleContext. 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
Source File: StackTraceColorizer.java    From otroslogviewer with 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 #2
Source File: ImageToggleButton.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ImageToggleButton( final ImageIcon icon,
                          final String text,
                          final GlobalPane.Alignment alignment ) {
  super();
  this.imageIcon = icon;
  this.text = text;

  setMargin( new Insets( 0, 0, 0, 0 ) );
  setContentAreaFilled( false );
  setBorderPainted( false );
  setBorder( BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) );
  setFont( StyleContext.getDefaultStyleContext().getFont( getFont().getName(), Font.PLAIN, 10 ) );
  setAlignmentX( alignment );

  setFocusable( false );
}
 
Example #3
Source File: AboutDialog.java    From Spade with GNU General Public License v3.0 6 votes vote down vote up
public static void addStylesToDocument(StyledDocument doc)
{
	//Initialize some styles.
	Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
	
	Style regular = doc.addStyle("regular", def);
	StyleConstants.setFontFamily(def, "SansSerif");
	
	Style s = doc.addStyle("italic", regular);
	StyleConstants.setItalic(s, true);
	
	s = doc.addStyle("bold", regular);
	StyleConstants.setBold(s, true);
	
	s = doc.addStyle("small", regular);
	StyleConstants.setFontSize(s, 10);
	
	s = doc.addStyle("large", regular);
	StyleConstants.setFontSize(s, 16);
	StyleConstants.setBold(s, true);
}
 
Example #4
Source File: OutputPanel.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Component createSearchPanel() {
    StyleContext styleContent = StyleContext.getDefaultStyleContext();

    AttributeSet highlightStyle = gradleOutputTextPane.getDefaultStyle().copyAttributes();
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Foreground, Color.white);
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Background, Color.orange);
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Underline, true);

    AttributeSet emphasizedHighlightStyle = highlightStyle.copyAttributes();
    emphasizedHighlightStyle = styleContent.addAttribute(emphasizedHighlightStyle, StyleConstants.Foreground, Color.black);
    emphasizedHighlightStyle = styleContent.addAttribute(emphasizedHighlightStyle, StyleConstants.Background, Color.yellow);

    searchPanel = new SearchPanel(new OutputPanelSearchInteraction(gradleOutputTextPane.getTextComponent(), gradleOutputTextPane.getDefaultStyle(), highlightStyle, emphasizedHighlightStyle));
    searchPanel.hide();

    return searchPanel.getComponent();
}
 
Example #5
Source File: OutputPanel.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Component createSearchPanel() {
    StyleContext styleContent = StyleContext.getDefaultStyleContext();

    AttributeSet highlightStyle = gradleOutputTextPane.getDefaultStyle().copyAttributes();
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Foreground, Color.white);
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Background, Color.orange);
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Underline, true);

    AttributeSet emphasizedHighlightStyle = highlightStyle.copyAttributes();
    emphasizedHighlightStyle = styleContent.addAttribute(emphasizedHighlightStyle, StyleConstants.Foreground, Color.black);
    emphasizedHighlightStyle = styleContent.addAttribute(emphasizedHighlightStyle, StyleConstants.Background, Color.yellow);

    searchPanel = new SearchPanel(new OutputPanelSearchInteraction(gradleOutputTextPane.getTextComponent(), gradleOutputTextPane.getDefaultStyle(), highlightStyle, emphasizedHighlightStyle));
    searchPanel.hide();

    return searchPanel.getComponent();
}
 
Example #6
Source File: MessageColorizerEditor.java    From otroslogviewer with 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 #7
Source File: PacketDetailPanel.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void showPacket(final AbstractPacketPoint point) {
	SwingUtilities4.invokeInEDT(() -> {
		final String[] lines = point.getPayload().split("\n");
		int max = 0;
		for (final String line1 : lines) {
			max = Math.max(max, line1.length());
		}
		max += 5;
		for (final String line2 : lines) {
			final Color color = colorForLine(line2);
			final StyleContext sc = StyleContext.getDefaultStyleContext();
			AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLACK);

			aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
			aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
			aset = sc.addAttribute(aset, StyleConstants.Bold, false);
			aset = sc.addAttribute(aset, StyleConstants.Background, color);
			final int len = _details.getDocument().getLength();
			_details.setCaretPosition(len);
			_details.setCharacterAttributes(aset, false);
			_details.replaceSelection(line2 + StringUtils.repeat(" ", max - line2.length()) + "\n");
		}
		_details.setCaretPosition(0);
	});
}
 
Example #8
Source File: MemoryStatusGadget.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public MemoryStatusGadget() {
  if ( MacOSXIntegration.MAC_OS_X ) {
    setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 10 ),
      BorderFactory.createLineBorder( SystemColor.controlShadow ) ) );
  } else {
    setBorder( BorderFactory.createLineBorder( SystemColor.controlShadow ) );
  }
  setFont(
    StyleContext.getDefaultStyleContext().getFont( getFont().getName(), Font.PLAIN, getFont().getSize() - 2 ) );
  setHorizontalAlignment( JLabel.CENTER );

  timer = new Timer( 500, new MemoryStatusUpdateAction() );
  timer.setRepeats( true );
  timer.start();

  addMouseListener( new GarbageCollectorAction() );
}
 
Example #9
Source File: MainPanel.java    From java-swing-tips with 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 #10
Source File: ConsoleSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected void addStylesToDocument(JTextPane outputArea) {
    StyledDocument doc = outputArea.getStyledDocument();

    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "Monospaced");

    promptStyle = doc.addStyle("prompt", regular);
    StyleConstants.setForeground(promptStyle, Color.BLUE);

    commandStyle = doc.addStyle("command", regular);
    StyleConstants.setForeground(commandStyle, Color.MAGENTA);

    outputStyle = doc.addStyle("output", regular);
    StyleConstants.setBold(outputStyle, true);
}
 
Example #11
Source File: OutputPanel.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Component createSearchPanel() {
    StyleContext styleContent = StyleContext.getDefaultStyleContext();

    AttributeSet highlightStyle = gradleOutputTextPane.getDefaultStyle().copyAttributes();
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Foreground, Color.white);
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Background, Color.orange);
    highlightStyle = styleContent.addAttribute(highlightStyle, StyleConstants.Underline, true);

    AttributeSet emphasizedHighlightStyle = highlightStyle.copyAttributes();
    emphasizedHighlightStyle = styleContent.addAttribute(emphasizedHighlightStyle, StyleConstants.Foreground, Color.black);
    emphasizedHighlightStyle = styleContent.addAttribute(emphasizedHighlightStyle, StyleConstants.Background, Color.yellow);

    searchPanel = new SearchPanel(new OutputPanelSearchInteraction(gradleOutputTextPane.getTextComponent(), gradleOutputTextPane.getDefaultStyle(), highlightStyle, emphasizedHighlightStyle));
    searchPanel.hide();

    return searchPanel.getComponent();
}
 
Example #12
Source File: CSS.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException
{
    ObjectInputStream.GetField f = s.readFields();
    int newBaseFontSize = f.get("baseFontSize", 0);
    setBaseFontSize(newBaseFontSize);

    // Reconstruct the hashtable.
    int numValues = s.readInt();
    valueConvertor = new Hashtable<>();
    while (numValues-- > 0) {
        Object key = s.readObject();
        Object value = s.readObject();
        Object staticKey = StyleContext.getStaticAttribute(key);
        if (staticKey != null) {
            key = staticKey;
        }
        Object staticValue = StyleContext.getStaticAttribute(value);
        if (staticValue != null) {
            value = staticValue;
        }
        if (key != null && value != null) {
            valueConvertor.put(key, value);
        }
    }
}
 
Example #13
Source File: FontUtils.java    From jadx with Apache License 2.0 6 votes vote down vote up
public static Font loadByStr(String fontDesc) {
	String[] parts = fontDesc.split("-");
	if (parts.length != 3) {
		throw new JadxRuntimeException("Unsupported font description format: " + fontDesc);
	}
	String name = parts[0];
	int style = parseFontStyle(parts[1]);
	int size = Integer.parseInt(parts[2]);

	StyleContext sc = StyleContext.getDefaultStyleContext();
	Font font = sc.getFont(name, style, size);
	if (font == null) {
		throw new JadxRuntimeException("Font not found: " + fontDesc);
	}
	return font;
}
 
Example #14
Source File: GroupingHeaderCellRenderer.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Component getTableCellRendererComponent( final JTable table, final Object value, final boolean isSelected,
                                                final boolean hasFocus, final int row, final int column ) {

  final JLabel label =
    (JLabel) super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
  if ( value == null ) {
    return label;
  }
  label.setBackground( Color.GRAY );
  label.setForeground( Color.WHITE );
  if ( column >= 1 ) {
    label.setText( "" ); //$NON-NLS-1$
    label.setIcon( null );
  } else {
    final Font font = StyleContext.getDefaultStyleContext().getFont( label.getFont().getName(), Font.BOLD,
      label.getFont().getSize() );
    label.setFont( font );
    final GroupingHeader groupingHeader = (GroupingHeader) value;
    final boolean isCollapsed = groupingHeader.isCollapsed();
    if ( table.getModel() instanceof GroupedTableModel ) {
      label.setIcon( isCollapsed ? expandImage : collapseImage );
    }
  }
  return label;
}
 
Example #15
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
@Override public void updateUI() {
  super.updateUI();
  setOpaque(false);
  putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
  EventQueue.invokeLater(() -> {
    // MutableAttributeSet attr = new SimpleAttributeSet();
    Style attr = getStyle(StyleContext.DEFAULT_STYLE);
    TabStop[] ts = {new TabStop(25f, TabStop.ALIGN_DECIMAL, TabStop.LEAD_NONE)};
    StyleConstants.setTabSet(attr, new TabSet(ts));
    setParagraphAttributes(attr, false);
  });
}
 
Example #16
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private MainPanel() {
  super(new BorderLayout(5, 5));
  JButton ok = new JButton("Test");
  ok.addActionListener(e -> append("Test test test test", true));

  JButton err = new JButton("Error");
  err.addActionListener(e -> append("Error error error error", false));

  JButton clr = new JButton("Clear");
  clr.addActionListener(e -> jtp.setText(""));

  Box box = Box.createHorizontalBox();
  box.add(Box.createHorizontalGlue());
  box.add(ok);
  box.add(err);
  box.add(Box.createHorizontalStrut(5));
  box.add(clr);

  jtp.setEditable(false);
  StyledDocument doc = jtp.getStyledDocument();
  // Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
  Style def = doc.getStyle(StyleContext.DEFAULT_STYLE);

  // Style regular = doc.addStyle("regular", def);
  // StyleConstants.setForeground(def, Color.BLACK);

  Style error = doc.addStyle("error", def);
  StyleConstants.setForeground(error, Color.RED);

  JScrollPane scroll = new JScrollPane(jtp);
  scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  scroll.getVerticalScrollBar().setUnitIncrement(25);

  add(scroll);
  add(box, BorderLayout.SOUTH);
  setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
  setPreferredSize(new Dimension(320, 240));
}
 
Example #17
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
protected SimpleSyntaxDocument() {
  super();
  // Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
  Style def = getStyle(StyleContext.DEFAULT_STYLE);
  StyleConstants.setForeground(addStyle("red", def), Color.RED);
  StyleConstants.setForeground(addStyle("green", def), Color.GREEN);
  StyleConstants.setForeground(addStyle("blue", def), Color.BLUE);
}
 
Example #18
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private void applyHighlighting(String content, int line) {
  Element root = getDefaultRootElement();
  int startOffset = root.getElement(line).getStartOffset();
  int endOffset = root.getElement(line).getEndOffset() - 1;
  int lineLength = endOffset - startOffset;
  int contentLength = content.length();
  endOffset = endOffset >= contentLength ? contentLength - 1 : endOffset;
  setCharacterAttributes(startOffset, lineLength, getStyle(StyleContext.DEFAULT_STYLE), true);
  checkForTokens(content, startOffset, endOffset);
}
 
Example #19
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  JTextPane textPane = new JTextPane();
  textPane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
  FontMetrics fm = textPane.getFontMetrics(textPane.getFont());
  float charWidth = fm.charWidth('m');
  float tabWidth = charWidth * 4f;
  TabStop[] tabs = new TabStop[10];
  for (int j = 0; j < tabs.length; j++) {
    tabs[j] = createTabStop((j + 1) * tabWidth);
  }
  TabSet tabSet = new TabSet(tabs);
  // MutableAttributeSet attributes = new SimpleAttributeSet();
  MutableAttributeSet attributes = textPane.getStyle(StyleContext.DEFAULT_STYLE);
  StyleConstants.setTabSet(attributes, tabSet);
  // int length = textPane.getDocument().getLength();
  // textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
  textPane.setParagraphAttributes(attributes, false);
  textPane.setText("JTextPane\n0123\n\t4567\n\t\t89ab\n");

  JTextArea textArea = new JTextArea();
  textArea.setTabSize(4);
  textArea.setText("JTextArea\n0123\n\t4567\n\t\t89ab\n");

  add(new JScrollPane(textArea), BorderLayout.NORTH);
  add(new JScrollPane(textPane));
  setPreferredSize(new Dimension(320, 240));
}
 
Example #20
Source File: MWPaneFormatter.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Clean format of a MediaWikiPane.
 * 
 * @param doc Styled document to be formatted.
 */
protected void cleanFormat(StyledDocument doc) {

  // Basic verifications
  if (doc == null) {
    return;
  }

  // Clean formation element by element
  doc.setCharacterAttributes(
      0, doc.getLength(),
      doc.getStyle(StyleContext.DEFAULT_STYLE),
      true);
}
 
Example #21
Source File: bug7189299.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void verifySingleDefaultButtonModelListener() {
    HTMLEditorKit htmlEditorKit = (HTMLEditorKit) html.getEditorKit();
    StyleContext.NamedStyle style = ((StyleContext.NamedStyle) htmlEditorKit
            .getInputAttributes());
    DefaultButtonModel model = ((DefaultButtonModel) style
            .getAttribute(StyleConstants.ModelAttribute));
    ActionListener[] listeners = model.getActionListeners();
    int actionListenerNum = listeners.length;
    if (actionListenerNum != 1) {
        throw new RuntimeException(
                "Expected single ActionListener object registered with "
                + "DefaultButtonModel; found " + actionListenerNum
                + " listeners registered.");
    }

    int changeListenerNum = model.getChangeListeners().length;
    if (changeListenerNum != 1) {
        throw new RuntimeException(
                "Expected at most one ChangeListener object registered "
                + "with DefaultButtonModel; found " + changeListenerNum
                + " listeners registered.");
    }
    int itemListenerNum = model.getItemListeners().length;
    if (itemListenerNum != 1) {
        throw new RuntimeException(
                "Expected at most one ItemListener object registered "
                + "with DefaultButtonModel; found " + itemListenerNum
                + " listeners registered.");
    }
}
 
Example #22
Source File: SmartDocumentFilter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public SmartDocumentFilter(DefaultStyledDocument styledDocument) {
    this.styledDocument = styledDocument;

    this.styleContext = StyleContext.getDefaultStyleContext();
    this.defaultStyle = this.styleContext.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setFontFamily(this.defaultStyle, MONOSPACED);

    initStyles();
}
 
Example #23
Source File: MagicTextPane.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public void updateTextWithIcons() {

		textPane.setText(textPane.getText().replaceAll("(?m)^[ \t]*\r?\n", ""));
		Pattern p = Pattern.compile(CardsPatterns.MANA_PATTERN.getPattern());
		Matcher m = p.matcher(textPane.getText());

		String text = textPane.getText();
		StyleContext context = new StyleContext();
		StyledDocument document = new DefaultStyledDocument(context);

		Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

		Style italic = context.addStyle("italicStyle", labelStyle);
		StyleConstants.setItalic(italic, true);

		int cumule = 0;
		try {
			document.insertString(0, text, null);
			while (m.find()) {
				Image ic = manaPanel.getManaSymbol(m.group());

				int width = 15;
				if (m.group().equals("{100}"))
					width = 30;

				JLabel label = new JLabel(new ImageIcon(ic.getScaledInstance(width, 15, Image.SCALE_DEFAULT)));
				label.setAlignmentY(SwingConstants.TOP);

				StyleConstants.setComponent(labelStyle, label);

				document.remove(m.start() + cumule, (m.end() - m.start()));
				document.insertString(m.start() + cumule, m.group(), labelStyle);
			}

			textPane.setDocument(document);
		} catch (BadLocationException e) {
			textPane.setText(text);
		}
	}
 
Example #24
Source File: TextStyleEditorPanel.java    From jclic with GNU General Public License v2.0 5 votes vote down vote up
public final void setStyleContext(StyleContext styleContext) {
  sc = (styleContext == null ? getEmptySc() : styleContext);
  TextActivityDocument.checkStyleContext(sc);
  Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);

  fontFaceCombo.setSelectedItem(StyleConstants.getFontFamily(defaultStyle));
  fontSizeCombo.setSelectedItem(Integer.toString(StyleConstants.getFontSize(defaultStyle)));
  boldBtn.setSelected(StyleConstants.isBold(defaultStyle));
  italicBtn.setSelected(StyleConstants.isItalic(defaultStyle));
  underlineBtn.setSelected(StyleConstants.isUnderline(defaultStyle));
  bgColorBtn.setColor(StyleConstants.getBackground(defaultStyle));

  textColorBtn.setColor(StyleConstants.getForeground(defaultStyle));

  int tabSpc = TextActivityDocument.DEFAULT_TAB;
  Object o = defaultStyle.getAttribute(TextActivityDocument.TABSPC);
  if (o != null) {
    try {
      tabSpc = Math.max(1, Math.min(Integer.parseInt(o.toString()), 50));
    } catch (Exception ex) {
      // ???
    }
  }
  tabSlider.setValue(tabSpc);

  Style targetStyle = sc.getStyle(TextActivityDocument.TARGET);
  targetBgColor.setColor(StyleConstants.getBackground(targetStyle));
  targetFgColor.setColor(StyleConstants.getForeground(targetStyle));

  Style errorStyle = sc.getStyle(TextActivityDocument.TARGET_ERROR);
  errorBgColor.setColor(StyleConstants.getBackground(errorStyle));
  errorFgColor.setColor(StyleConstants.getForeground(errorStyle));

  updatePreview(null);
}
 
Example #25
Source File: KTextEdit.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add text using a style defined for a notification type.
 *
 * @param text text contents
 * @param type type for formatting
 */
protected void insertText(final String text, final NotificationType type) {
	ChatTextSink dest = new ChatTextSink(textPane.getDocument());
	StyleSet set = new StyleSet(StyleContext.getDefaultStyleContext(), getStyle(type.getColor(), type.getStyleDescription()));
	set.setAttribute(StyleConstants.Foreground, type.getColor());

	formatter.format(text, set, dest);
}
 
Example #26
Source File: ColoredJTextPane.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
public ColoredJTextPane() {
	super();
	setDocument(new DefaultStyledDocument() {

		private static final long serialVersionUID = 1L;

		@Override
		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
			super.insertString(offs, str, a);

			// now color all texts again
			// do coloring of words but ignore keys unless it is word termination
			String text = getText(0, getLength());
			char[] chars = text.toCharArray();
			StyleContext context = StyleContext.getDefaultStyleContext();
			int lastStart = 0;
			boolean charactersSinceLastStart = false;
			for (int i = 0; i < text.length(); i++) {
				if (!Character.isLetter(chars[i])) {
					if (charactersSinceLastStart) {
						AttributeSet attributeSet = context.addAttribute(SimpleAttributeSet.EMPTY,
								StyleConstants.Foreground, getColor(new String(chars, lastStart, i - lastStart)));
						setCharacterAttributes(lastStart, i - lastStart, attributeSet, true);
					}
					lastStart = i + 1;
					charactersSinceLastStart = false;
				} else {
					charactersSinceLastStart = true;
				}
			}
		}
	});

}
 
Example #27
Source File: FontTools.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This should be called during the GUI initialization after applying LAF. The UI fonts will be
 * replaced according to the user's wishes.
 */
public static void checkAndSetFallbackUIFont() {
	String fontConfig = getFontConfig();
	if (OPTION_STANDARD_FONTS.equals(fontConfig)) {
		return;
	}

	Enumeration<Object> keys = UIManager.getDefaults().keys();
	while (keys.hasMoreElements()) {
		Object key = keys.nextElement();
		Object value = UIManager.get(key);
		if (value instanceof FontUIResource) {
			FontUIResource orig = (FontUIResource) value;
			String family = orig.getFamily();

			if (OPTION_SYSTEM_FONTS.equals(fontConfig)) {
				// replace all non-system fonts with SYSTEM_FALLBACK_FONT
				if (LOGICAL_FONT_FAMILIES.contains(family)) {
					continue;
				}
				family = SYSTEM_FALLBACK_FONT;
			} else {
				// replace all fonts with specified family
				if (family.equals(fontConfig)) {
					continue;
				}
				family = fontConfig;
			}

			Font font = StyleContext.getDefaultStyleContext().getFont(family, orig.getStyle(), orig.getSize());
			UIManager.put(key, new FontUIResource(font));
		}
	}
}
 
Example #28
Source File: MASConsoleColorGUI.java    From jason with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void append(Color c, String s) {
    if (c == null)
        c = defaultColor;
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet as = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
    try {
        getDocument().insertString(getDocument().getLength(), s, as);
    } catch (BadLocationException e) {
    }
}
 
Example #29
Source File: MultiAnnotViewerFrame.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Inits the.
 *
 * @param text the text
 * @param extents the extents
 */
public void init(String text, MarkupExtent[] extents) {
  this.textPane = new JTextPane();
  this.scrollPane = new JScrollPane(this.textPane);
  this.setContentPane(this.scrollPane);
  Document doc = this.textPane.getDocument();
  Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
  Style level0 = this.textPane.addStyle("level0", def);
  Style level1 = this.textPane.addStyle("level1", level0);
  StyleConstants.setBackground(level1, Color.green);
  Style level2 = this.textPane.addStyle("level2", level0);
  StyleConstants.setBackground(level2, Color.yellow);
  Style level3 = this.textPane.addStyle("level3", level0);
  StyleConstants.setBackground(level3, Color.orange);
  Style[] styleArray = { level0, level1, level2, level3 };
  System.out.println("  Creating the text.");
  MarkupExtent e;
  int level;
  String s;
  try {
    for (int i = 0; i < extents.length; i++) {
      e = extents[i];
      level = e.getMarkupDepth();
      if (level > 3) {
        level = 3;
      }
      s = text.substring(e.getStart(), e.getEnd());
      doc.insertString(doc.getLength(), s, styleArray[level]);
      // System.out.println("Adding text: \"" + s + "\"\nat level: " +
      // level);
    }
  } catch (Exception ex) {
    ex.printStackTrace();
  }
  this.textPane.getCaret().setDot(0);
  System.out.println("  Packing frame.");
  this.pack();
  System.out.println("  Showing frame.");
  this.setVisible(true);
}
 
Example #30
Source File: FlatLaf.java    From FlatLaf with Apache License 2.0 5 votes vote down vote up
static FontUIResource createCompositeFont( String family, int style, int size ) {
	// using StyleContext.getFont() here because it uses
	// sun.font.FontUtilities.getCompositeFontUIResource()
	// and creates a composite font that is able to display all Unicode characters
	Font font = StyleContext.getDefaultStyleContext().getFont( family, style, size );
	return (font instanceof FontUIResource) ? (FontUIResource) font : new FontUIResource( font );
}