Java Code Examples for javax.swing.text.StyleConstants

The following examples show how to use javax.swing.text.StyleConstants. 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
Source Project: org.alloytools.alloy   Source File: OurConsole.java    License: Apache License 2.0 6 votes vote down vote up
static MutableAttributeSet style(String fontName, int fontSize, boolean boldness, boolean italic, boolean strike, Color color, int leftIndent) {


        fontName = AlloyGraphics.matchBestFontName(fontName);

        MutableAttributeSet s = new SimpleAttributeSet();
        StyleConstants.setFontFamily(s, fontName);
        StyleConstants.setFontSize(s, fontSize);
        StyleConstants.setLineSpacing(s, -0.2f);
        StyleConstants.setBold(s, boldness);
        StyleConstants.setItalic(s, italic);
        StyleConstants.setForeground(s, color);
        StyleConstants.setLeftIndent(s, leftIndent);
        StyleConstants.setStrikeThrough(s, strike);
        return s;
    }
 
Example 2
Source Project: netbeans   Source File: ViewFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
public View create(Element elem) {
    String kind = elem.getName();
    if (kind != null) {
        if (kind.equals(AbstractDocument.ContentElementName)) {
            return new LabelView(elem);
        } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
            return null;
        } else if (kind.equals(AbstractDocument.SectionElementName)) {
            return new DocumentView(elem);
        } else if (kind.equals(StyleConstants.ComponentElementName)) {
            return new ComponentView(elem);
        } else if (kind.equals(StyleConstants.IconElementName)) {
            return new IconView(elem);
        }
    }
    return null;
}
 
Example 3
Source Project: netbeans   Source File: ColorsManager.java    License: Apache License 2.0 6 votes vote down vote up
private static Map getCurrentColors(Language l) {
    // current colors
    FontColorSettingsFactory fcsf = EditorSettings.getDefault().
            getFontColorSettings(new String[] {l.getMimeType()});
    Collection<AttributeSet> colors = fcsf.getAllFontColors("NetBeans");
    Map<String,AttributeSet> colorsMap = new HashMap<String,AttributeSet> ();
    Iterator<AttributeSet> it = colors.iterator();
    while (it.hasNext()) {
        AttributeSet as = it.next();
        colorsMap.put(
                (String) as.getAttribute(StyleConstants.NameAttribute),
                as
                );
    }
    return colorsMap;
}
 
Example 4
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 5
Source Project: WorldGrower   Source File: JTextPaneUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void appendTextUsingLabel(JTextPane textPane, String message) {
	StyledDocument document = (StyledDocument)textPane.getDocument();
	
       try {
		JLabel jl  = JLabelFactory.createJLabel(message);
		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: groovy   Source File: ConsoleSupport.java    License: 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 7
@Override
public javax.swing.text.View create(Element elem) {
    String kind = elem.getName();
    if (kind != null) {
        switch (kind) {
            case AbstractDocument.ContentElementName:
                return new WrapLabelView(elem);
            case AbstractDocument.ParagraphElementName:
                return new ParagraphView(elem);
            case AbstractDocument.SectionElementName:
                return new BoxView(elem, javax.swing.text.View.Y_AXIS);
            case StyleConstants.ComponentElementName:
                return new ComponentView(elem);
            case StyleConstants.IconElementName:
                return new IconView(elem);
        }
    }
    // default to text display
    return new LabelView(elem);
}
 
Example 8
Source Project: SikuliX1   Source File: PythonIndentation.java    License: MIT License 6 votes vote down vote up
@Override
public String getLeadingWhitespace(StyledDocument doc, int head, int len) throws BadLocationException {
  String ret = "";
  int pos = head;
  while (pos < head + len) {
    Element e = doc.getCharacterElement(pos);
    if (e.getName().equals(StyleConstants.ComponentElementName)) {
      break;
    }
    int eStart = e.getStartOffset();
    int eEnd = e.getEndOffset();
    String space = getLeadingWhitespace(doc.getText(eStart, eEnd - eStart));
    ret += space;
    if (space.length() < eEnd - eStart) {
      break;
    }
    pos = eEnd;
  }
  return ret;
}
 
Example 9
Source Project: stendhal   Source File: KTextEdit.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public View create(Element elem) {
	String kind = elem.getName();
	if (kind != null) {
		if (kind.equals(AbstractDocument.ContentElementName)) {
			return new WrapLabelView(elem);
		} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
			return new ParagraphView(elem);
		} else if (kind.equals(AbstractDocument.SectionElementName)) {
			return new BoxView(elem, View.Y_AXIS);
		} else if (kind.equals(StyleConstants.ComponentElementName)) {
			return new ComponentView(elem);
		} else if (kind.equals(StyleConstants.IconElementName)) {
			return new IconView(elem);
		}
	}

	// default to text display
	return new LabelView(elem);
}
 
Example 10
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 11
@Override
public void actionPerformed(ActionEvent event) {
  Style style = AnnotationDisplayCustomizationFrame.this.styleMap
      .get(AnnotationDisplayCustomizationFrame.this.currentTypeName);
  if (style == null) {
    style = AnnotationDisplayCustomizationFrame.this.textPane.addStyle(
        AnnotationDisplayCustomizationFrame.this.currentTypeName,
        AnnotationDisplayCustomizationFrame.this.styleMap.get(CAS.TYPE_NAME_ANNOTATION));
  }
  StyleConstants.setForeground(style, StyleConstants
      .getForeground(AnnotationDisplayCustomizationFrame.this.currentStyle));
  StyleConstants.setBackground(style, StyleConstants
      .getBackground(AnnotationDisplayCustomizationFrame.this.currentStyle));
  AnnotationDisplayCustomizationFrame.this.styleMap.put(
      AnnotationDisplayCustomizationFrame.this.currentTypeName, style);
  enableButtons(false);
  AnnotationDisplayCustomizationFrame.this.repaint();
}
 
Example 12
Source Project: hortonmachine   Source File: WrapEditorKit.java    License: GNU General Public License v3.0 6 votes vote down vote up
public View create( Element elem ) {
    String kind = elem.getName();
    if (kind != null) {
        if (kind.equals(AbstractDocument.ContentElementName)) {
            return new WrapLabelView(elem);
        } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
            return new ParagraphView(elem);
        } else if (kind.equals(AbstractDocument.SectionElementName)) {
            return new BoxView(elem, View.Y_AXIS);
        } else if (kind.equals(StyleConstants.ComponentElementName)) {
            return new ComponentView(elem);
        } else if (kind.equals(StyleConstants.IconElementName)) {
            return new IconView(elem);
        }
    }

    // default to text display
    return new LabelView(elem);
}
 
Example 13
Source Project: netbeans   Source File: SyntaxColoringPanel.java    License: Apache License 2.0 6 votes vote down vote up
private Collection<AttributeSet> invertCategory (Collection<AttributeSet> c, AttributeSet category) {
    if (category == null) return c;
    ArrayList<AttributeSet> result = new ArrayList<AttributeSet> (c);
    int i = result.indexOf (category);
    SimpleAttributeSet as = new SimpleAttributeSet (category);
    Color highlight = (Color) getValue (currentLanguage, category, StyleConstants.Background);
    if (highlight == null) return result;
    Color newColor = new Color (
        255 - highlight.getRed (),
        255 - highlight.getGreen (),
        255 - highlight.getBlue ()
    );
    as.addAttribute (
        StyleConstants.Underline,
        newColor
    );
    result.set (i, as);
    return result;
}
 
Example 14
Source Project: netbeans   Source File: QueryBuilderSqlTextArea.java    License: Apache License 2.0 6 votes vote down vote up
public QueryBuilderSqlTextArea(QueryBuilder queryBuilder) {
        super();
        _queryBuilder = queryBuilder;
        createSqlTextPopup();
        // Get Netbeans-registered EditorKit for SQL content
	setEditorKit(CloneableEditorSupport.getEditorKit("text/x-sql"));
        if ( SYNTAX_HIGHLIGHT ) {
            addKeyListener(this);
        }
        
        // set the bold attribute
        // colors chosen from :
        // http://ui.netbeans.org/docs/hi/annotations/index2.html
        StyleConstants.setForeground(keyword,new Color(0,0,153));
        StyleConstants.setForeground(schema, new Color(0,111,0));
        StyleConstants.setForeground(column,new Color(120,0,0));
          
        // Add support for code completion (comment out, breaks syntax highlighting)
//        QueryBuilderSqlCompletion doc = new QueryBuilderSqlCompletion( this, sqlReservedWords);
//        this.setDocument(doc);
    }
 
Example 15
/**
 * Creates a new {@link LogRecordEntry} which automatically formats the given {@link LogRecord}
 * with the RapidMiner Studio log styling and default logging format.
 *
 * @param logRecord
 */
public LogRecordEntry(LogRecord logRecord) {

	logLevel = logRecord.getLevel();
	initialString = logRecord.getMessage();

	simpleAttributeSet = new SimpleAttributeSet();
	if (logRecord.getLevel().intValue() >= Level.SEVERE.intValue()) {
		StyleConstants.setForeground(simpleAttributeSet, COLOR_ERROR);
		StyleConstants.setBold(simpleAttributeSet, true);
	} else if (logRecord.getLevel().intValue() >= Level.WARNING.intValue()) {
		StyleConstants.setForeground(simpleAttributeSet, COLOR_WARNING);
		StyleConstants.setBold(simpleAttributeSet, true);
	} else if (logRecord.getLevel().intValue() >= Level.INFO.intValue()) {
		StyleConstants.setForeground(simpleAttributeSet, COLOR_INFO);
		StyleConstants.setBold(simpleAttributeSet, false);
	} else {
		StyleConstants.setForeground(simpleAttributeSet, COLOR_DEFAULT);
		StyleConstants.setBold(simpleAttributeSet, false);
	}

	formattedString = formatter.format(logRecord);
}
 
Example 16
Source Project: android-classyshark   Source File: DisplayArea.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void displaySharkey() {
    displayDataState = DisplayDataState.SHARKEY;
    clearText();
    style = jTextPane.addStyle("STYLE", null);
    Document doc = jTextPane.getStyledDocument();

    try {
        StyleConstants.setForeground(style, theme.getIdentifiersColor());
        StyleConstants.setFontSize(style, 15);
        StyleConstants.setFontFamily(style, "Monospaced");

        doc.insertString(doc.getLength(), Doodle.get(), style);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }

    jTextPane.setDocument(doc);
}
 
Example 17
Source Project: netbeans   Source File: RefactoringUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static String color(String string, AttributeSet set) {
    if (set == null) {
        return string;
    }
    if (string.trim().length() == 0) {
        return string.replace(" ", "&nbsp;").replace("\n", "<br>"); //NOI18N

    }
    StringBuilder buf = new StringBuilder(string);
    if (StyleConstants.isBold(set)) {
        buf.insert(0, "<b>"); //NOI18N

        buf.append("</b>"); //NOI18N

    }
    if (StyleConstants.isItalic(set)) {
        buf.insert(0, "<i>"); //NOI18N

        buf.append("</i>"); //NOI18N

    }
    if (StyleConstants.isStrikeThrough(set)) {
        buf.insert(0, "<s>"); // NOI18N

        buf.append("</s>"); // NOI18N

    }
    buf.insert(0, "<font color=" + getHTMLColor(StyleConstants.getForeground(set)) + ">"); //NOI18N

    buf.append("</font>"); //NOI18N

    return buf.toString();
}
 
Example 18
Source Project: darklaf   Source File: ColoredTextDemo.java    License: MIT License 5 votes vote down vote up
@Override
protected JTextPane createTextComponent() {
    JTextPane textPane = super.createTextComponent();
    textPane.getDocument().addDocumentListener((InsertDocumentListener) () -> SwingUtilities.invokeLater(() -> {
        StyledDocument document = textPane.getStyledDocument();
        Random r = new Random();
        for (int i = 0; i < document.getLength() - 2; i++) {
            MutableAttributeSet a = new SimpleAttributeSet();
            Color c = DarkColorModelHSB.getColorFromHSBValues(r.nextDouble(), 1, 1);
            StyleConstants.setForeground(a, c);
            document.setCharacterAttributes(i, 1, a, true);
        }
    }));
    return textPane;
}
 
Example 19
Source Project: myqq   Source File: MyTextPane.java    License: MIT License 5 votes vote down vote up
/**
 * 获取某种字体
 * @param name 字体名称
 * @param size 字体大小
 * @param color 字体颜色
 * @param bold 是否加粗
 * @param underline 是否加下划线
 * @return 返回获取的字体
 */
public static SimpleAttributeSet getFontAttribute(String name, int size, Color color,
		boolean bold, boolean underline)
{
	SimpleAttributeSet attribute = new SimpleAttributeSet();
	StyleConstants.setFontFamily(attribute, name);
	StyleConstants.setFontSize(attribute, size);
	StyleConstants.setForeground(attribute, color);
	StyleConstants.setBold(attribute, bold);
	StyleConstants.setUnderline(attribute, underline);
	return attribute;
}
 
Example 20
Source Project: jdk1.8-source-analysis   Source File: ParagraphView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets up the paragraph from css attributes instead of
 * the values found in StyleConstants (i.e. which are used
 * by the superclass).  Since
 */
protected void setPropertiesFromAttributes() {
    StyleSheet sheet = getStyleSheet();
    attr = sheet.getViewAttributes(this);
    painter = sheet.getBoxPainter(attr);
    if (attr != null) {
        super.setPropertiesFromAttributes();
        setInsets((short) painter.getInset(TOP, this),
                  (short) painter.getInset(LEFT, this),
                  (short) painter.getInset(BOTTOM, this),
                  (short) painter.getInset(RIGHT, this));
        Object o = attr.getAttribute(CSS.Attribute.TEXT_ALIGN);
        if (o != null) {
            // set horizontal alignment
            String ta = o.toString();
            if (ta.equals("left")) {
                setJustification(StyleConstants.ALIGN_LEFT);
            } else if (ta.equals("center")) {
                setJustification(StyleConstants.ALIGN_CENTER);
            } else if (ta.equals("right")) {
                setJustification(StyleConstants.ALIGN_RIGHT);
            } else if (ta.equals("justify")) {
                setJustification(StyleConstants.ALIGN_JUSTIFIED);
            }
        }
        // Get the width/height
        cssWidth = (CSS.LengthValue)attr.getAttribute(
                                    CSS.Attribute.WIDTH);
        cssHeight = (CSS.LengthValue)attr.getAttribute(
                                     CSS.Attribute.HEIGHT);
    }
}
 
Example 21
Source Project: trygve   Source File: TextEditorGUI.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ArrayList<Integer> breakpointByteOffsets() {
	State state = State.LookingForField;
	ArrayList<Integer> retval = new ArrayList<Integer>();
	
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final SimpleAttributeSet breakpointColored = new SimpleAttributeSet(); 
	StyleConstants.setBackground(breakpointColored, Color.cyan);
	
	for(int i = 0; i < doc.getLength(); i++) {
		final Element element = doc.getCharacterElement(i);
	    final AttributeSet set = element.getAttributes();
	    final Color backgroundColor = StyleConstants.getBackground(set);
	    switch (state) {
	    case LookingForField:
	    	if (true == backgroundColor.equals(Color.cyan)) {
	    		state = State.InField;
	    		retval.add(new Integer(i));
	    	}
	    	break;
	    case InField:
	    	if (false == backgroundColor.equals(Color.cyan)) {
	    		state = State.LookingForField;
	    	} else if (element.toString().equals("\n")) {
	    		state = State.LookingForField;
	    	}
	    	break;
	    default:
	    	assert (false);
	    	break;
	    }
	}
	
	return retval;
}
 
Example 22
Source Project: java-swing-tips   Source File: MainPanel.java    License: 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 23
Source Project: netbeans   Source File: HighlightingPanel.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, AttributeSet> toMap(Collection<AttributeSet> categories) {
    if (categories == null) return null;
    Map<String, AttributeSet> result = new HashMap<String, AttributeSet>();
    for(AttributeSet as : categories) {
        result.put((String) as.getAttribute(StyleConstants.NameAttribute), as);
    }
    return result;
}
 
Example 24
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 25
Source Project: jdk8u_jdk   Source File: ParagraphView.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets up the paragraph from css attributes instead of
 * the values found in StyleConstants (i.e. which are used
 * by the superclass).  Since
 */
protected void setPropertiesFromAttributes() {
    StyleSheet sheet = getStyleSheet();
    attr = sheet.getViewAttributes(this);
    painter = sheet.getBoxPainter(attr);
    if (attr != null) {
        super.setPropertiesFromAttributes();
        setInsets((short) painter.getInset(TOP, this),
                  (short) painter.getInset(LEFT, this),
                  (short) painter.getInset(BOTTOM, this),
                  (short) painter.getInset(RIGHT, this));
        Object o = attr.getAttribute(CSS.Attribute.TEXT_ALIGN);
        if (o != null) {
            // set horizontal alignment
            String ta = o.toString();
            if (ta.equals("left")) {
                setJustification(StyleConstants.ALIGN_LEFT);
            } else if (ta.equals("center")) {
                setJustification(StyleConstants.ALIGN_CENTER);
            } else if (ta.equals("right")) {
                setJustification(StyleConstants.ALIGN_RIGHT);
            } else if (ta.equals("justify")) {
                setJustification(StyleConstants.ALIGN_JUSTIFIED);
            }
        }
        // Get the width/height
        cssWidth = (CSS.LengthValue)attr.getAttribute(
                                    CSS.Attribute.WIDTH);
        cssHeight = (CSS.LengthValue)attr.getAttribute(
                                     CSS.Attribute.HEIGHT);
    }
}
 
Example 26
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 27
Source Project: jdk8u-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 28
Source Project: netbeans   Source File: ColorsManager.java    License: Apache License 2.0 5 votes vote down vote up
private static AttributeSet getUnusedLocalVariableAttributes () {
    if (unusedLocalVariableAttributeSet == null) {
        SimpleAttributeSet sas = new SimpleAttributeSet ();
        StyleConstants.setForeground (sas, new Color (115, 115, 115));
        unusedLocalVariableAttributeSet = sas;
    }
    return unusedLocalVariableAttributeSet;
}
 
Example 29
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 30
public
void setFontSize(int size) {
  Enumeration e = attributes.elements();
  while (e.hasMoreElements()) {
    StyleConstants.setFontSize((MutableAttributeSet)e.nextElement(),size);
  }
  return;
}