下面列出了怎么用javax.swing.text.Style的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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();
}
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);
}
}
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;
}
/**
* 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.");
}
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);
}
}
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));
}
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);
}
}
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);
}
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);
}
}
@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);
}
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);
}
/**
* 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);
}
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);
}
}
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);
}
}
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);
}
}
public void appendText(String text, Style style) {
StyledDocument doc = getStyledDocument();
try {
doc.insertString(doc.getLength(), text + "\n", style);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
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();
}
}
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;
}
static void testSuperScript() {
System.out.println("testSuperScript()");
bug8016833 b = new bug8016833() {
@Override
void setNormalStyle(Style style) {
StyleConstants.setSuperscript(style, true);
}
};
b.testUnderline();
b.testStrikthrough();
}
static void testSubScript() {
System.out.println("testSubScript()");
bug8016833 b = new bug8016833() {
@Override
void setNormalStyle(Style style) {
StyleConstants.setSubscript(style, true);
}
};
b.testUnderline();
b.testStrikthrough();
}
@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();
}
static void testSuperScript() {
System.out.println("testSuperScript()");
bug8016833 b = new bug8016833() {
@Override
void setNormalStyle(Style style) {
StyleConstants.setSuperscript(style, true);
}
};
b.testUnderline();
b.testStrikthrough();
}
static void testNormalScript() {
System.out.println("testNormalScript()");
bug8016833 b = new bug8016833() {
@Override
void setNormalStyle(Style style) {
}
};
b.testUnderline();
b.testStrikthrough();
}
static void testSubScript() {
System.out.println("testSubScript()");
bug8016833 b = new bug8016833() {
@Override
void setNormalStyle(Style style) {
StyleConstants.setSubscript(style, true);
}
};
b.testUnderline();
b.testStrikthrough();
}
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);
}
/**
* 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;
}
/**
* @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;
}
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();
}
}
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();
}
}
static void testSuperScript() {
System.out.println("testSuperScript()");
bug8016833 b = new bug8016833() {
@Override
void setNormalStyle(Style style) {
StyleConstants.setSuperscript(style, true);
}
};
b.testUnderline();
b.testStrikthrough();
}