下面列出了javax.swing.JTextPane#getStyledDocument ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void create() {
textPane = new JTextPane();
doc = textPane.getStyledDocument();
add(textPane, BorderLayout.CENTER);
textPane.setEditable(false);
headingAttrSet = new SimpleAttributeSet();
headingAttrSet.addAttribute(StyleConstants.FontFamily, "Monospaced");
headingAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
headingAttrSet.addAttribute(StyleConstants.Foreground, Color.BLUE);
valueAttrSet = new SimpleAttributeSet();
valueAttrSet.addAttribute(StyleConstants.FontFamily, "Tahoma");
valueAttrSet.addAttribute(StyleConstants.FontSize, new Integer(11));
valueAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
deletedAttrSet = new SimpleAttributeSet();
deletedAttrSet.addAttribute(StyleConstants.FontFamily, "Tahoma");
deletedAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
deletedAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
deletedAttrSet.addAttribute(StyleConstants.Foreground, Color.RED);
setSourceArchive(null);
}
/**
* Create the log pane, with a standard mailbox.
*/
public LogPane ()
{
// Build the scroll pane
component = new JScrollPane();
component.setBorder(null);
// log/status area
logArea = new JTextPane();
logArea.setEditable(false);
logArea.setMargin(new Insets(5, 5, 5, 5));
document = (AbstractDocument) logArea.getStyledDocument();
// Let the scroll pane display the log area
component.setViewportView(logArea);
}
@Override
public void mouseClicked(MouseEvent e) {
try {
if (SwingUtilities.isLeftMouseButton(e)) {
JTextPane pane = (JTextPane)e.getSource();
StyledDocument doc = pane.getStyledDocument();
Element elem = doc.getCharacterElement(pane.viewToModel(e.getPoint()));
AttributeSet as = elem.getAttributes();
Link link = (Link)as.getAttribute(LINK_ATTRIBUTE);
if (link != null) {
link.onClick(elem.getDocument().getText(elem.getStartOffset(), elem.getEndOffset() - elem.getStartOffset()));
}
}
} catch(Exception ex) {
Support.LOG.log(Level.SEVERE, null, ex);
}
}
private void addDate (JTextPane pane, RevisionItem item, boolean selected, Collection<SearchHighlight> highlights) throws BadLocationException {
LogEntry entry = item.getUserData();
StyledDocument sd = pane.getStyledDocument();
// clear document
clearSD(pane, sd);
Style selectedStyle = createSelectedStyle(pane);
Style normalStyle = createNormalStyle(pane);
Style style;
if (selected) {
style = selectedStyle;
} else {
style = normalStyle;
}
// add date
sd.insertString(sd.getLength(), entry.getDate(), style);
}
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);
}
public static void setStyle(JTextPane textPane, int start, int length,
String name)
{
StyledDocument doc = textPane.getStyledDocument();
Style style;
if (name == null)
{
StyleContext context = StyleContext.getDefaultStyleContext();
style = context.getStyle(StyleContext.DEFAULT_STYLE);
}
else
style = doc.getStyle(name);
doc.setCharacterAttributes(start, length, style, true);
}
public MatchingHighlighter(SmartDocumentFilter smartDocumentFilter, JTextPane textEditor) {
this.smartDocumentFilter = smartDocumentFilter;
this.textEditor = textEditor;
this.doc = (DefaultStyledDocument) textEditor.getStyledDocument();
initStyles();
}
ConsoleOutputStream(JTextPane textPane, Charset encoding, Style style, int maxLineCount) {
super(new ByteArrayOutputStream());
this.textPane = textPane;
this.encoding = encoding;
this.style = style;
this.maxLineCount = maxLineCount;
doc = textPane.getStyledDocument();
}
@Override
public void setVisible(boolean b) {
if (b) {
JTextPane pane = (JTextPane) getInvoker();
StyledDocument doc = pane.getStyledDocument();
Element elem = doc.getCharacterElement(pane.viewToModel(clickPoint));
Object l = elem.getAttributes().getAttribute(HyperlinkSupport.LINK_ATTRIBUTE);
if (l != null && l instanceof AttachmentLink) {
BugzillaIssue.Attachment attachment = ((AttachmentLink) l).attachment;
if (attachment != null) {
add(new JMenuItem(attachment.getOpenAction()));
add(new JMenuItem(attachment.getSaveAction()));
Action openInStackAnalyzerAction = attachment.getOpenInStackAnalyzerAction();
if(openInStackAnalyzerAction != null) {
add(new JMenuItem(openInStackAnalyzerAction));
}
if (attachment.isPatch()) {
Action a = attachment.getApplyPatchAction();
if(a != null) {
add(attachment.getApplyPatchAction());
}
}
super.setVisible(true);
}
}
} else {
super.setVisible(false);
removeAll();
}
}
/**
* Create the frame.
*/
public LicenseWindow(final String path) {
setTitle("Coder HPMSA - [License]");
setBounds(100, 100, 550, 550);
setBackground(Color.decode("#066d95"));
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setIconImage(Toolkit.getDefaultToolkit().
getImage(getClass().getResource(LOGOPATH)));
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
getContentPane().add(scrollPane, BorderLayout.CENTER);
editorPane = new JTextPane();
editorPane.setBackground(new Color(255, 255, 240));
editorPane.setFont(new Font("Verdana", Font.PLAIN, 13));
editorPane.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
editorPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
editorPane.setEditable(false);
scrollPane.setViewportView(editorPane);
final StyledDocument doc = editorPane.getStyledDocument();
final SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength()-1, center, false);
fillEditorPane(path);
setVisible(true);
}
private void create() {
textPane = new JTextPane();
textPane.setEditable(false);
add(textPane, BorderLayout.CENTER);
doc = textPane.getStyledDocument();
}
private void create() {
textPane = new JTextPane();
doc = textPane.getStyledDocument();
add(textPane, BorderLayout.CENTER);
textPane.setEditable(false);
pathAttrSet = new SimpleAttributeSet();
pathAttrSet.addAttribute(StyleConstants.FontFamily, "Tahoma");
pathAttrSet.addAttribute(StyleConstants.FontSize, new Integer(11));
pathAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
pathAttrSet.addAttribute(StyleConstants.Foreground, MergeConstants.CONFLICT_COLOR);
nameAttrSet = new SimpleAttributeSet();
nameAttrSet.addAttribute(StyleConstants.FontFamily, "Tahoma");
nameAttrSet.addAttribute(StyleConstants.FontSize, new Integer(11));
nameAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
sourceAttrSet = new SimpleAttributeSet();
sourceAttrSet.addAttribute(StyleConstants.FontFamily, "Tahoma");
sourceAttrSet.addAttribute(StyleConstants.FontSize, new Integer(11));
sourceAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
sourceAttrSet.addAttribute(StyleConstants.Foreground, SOURCE_COLOR);
offsetAttrSet = new SimpleAttributeSet();
offsetAttrSet.addAttribute(StyleConstants.FontFamily, "Monospaced");
offsetAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
offsetAttrSet.addAttribute(StyleConstants.Foreground, Color.BLACK);
contentAttrSet = new SimpleAttributeSet();
contentAttrSet.addAttribute(StyleConstants.FontFamily, "Monospaced");
contentAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
contentAttrSet.addAttribute(StyleConstants.Foreground, Color.BLUE);
fieldNameAttrSet = new SimpleAttributeSet();
fieldNameAttrSet.addAttribute(StyleConstants.FontFamily, "Monospaced");
fieldNameAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
fieldNameAttrSet.addAttribute(StyleConstants.Foreground, new Color(204, 0, 204));
commentAttrSet = new SimpleAttributeSet();
commentAttrSet.addAttribute(StyleConstants.FontFamily, "Monospaced");
commentAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
commentAttrSet.addAttribute(StyleConstants.Foreground, new Color(0, 204, 51));
deletedAttrSet = new SimpleAttributeSet();
deletedAttrSet.addAttribute(StyleConstants.FontFamily, "Tahoma");
deletedAttrSet.addAttribute(StyleConstants.FontSize, new Integer(12));
deletedAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
deletedAttrSet.addAttribute(StyleConstants.Foreground, Color.RED);
setDataType(dataType);
}
/**
* Constructs a {@link ClipboardFrame}.
*
* @param content
* the content as a string
*/
public ClipboardFrame(final String content) {
final JTextPane text = new JTextPane() {
private static final long serialVersionUID = 1L;
@Override
public void processMouseEvent(MouseEvent me) {
switch (me.getID()) {
case MouseEvent.MOUSE_CLICKED:
switch (me.getButton()) {
case MouseEvent.BUTTON1:
StringSelection stringSelection = new StringSelection(content);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, ClipboardFrame.this);
break;
default:
break;
}
ClipboardFrame.this.dispose();
break;
default:
break;
}
}
};
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
ClipboardFrame.this.dispose();
}
});
text.setCaretColor(Color.WHITE);
text.setEditable(false);
text.setHighlighter(null);
text.setBorder(BorderFactory.createLineBorder(Color.WHITE, 4));
final StyledDocument doc = text.getStyledDocument();
try {
doc.insertString(doc.getLength(), content, null);
doc.remove(doc.getLength() - 1, 1);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
JPanel panel = new JPanel(new BorderLayout());
panel.add(text);
panel.add(BorderLayout.SOUTH, new JLabel(" left-click: copy to clipboard"));
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
add(panel);
setUndecorated(true);
Point2D p = MouseInfo.getPointerInfo().getLocation();
setLocation((int) p.getX() - 8, (int) p.getY() - 8);
}
private void updateTextPaneImpl(JTextPane pane) throws BadLocationException {
Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
StyledDocument doc = pane.getStyledDocument();
Style boldStyle = doc.addStyle("bold", defaultStyle);
StyleConstants.setBold(boldStyle, true);
Style errorStyle = doc.addStyle("error", defaultStyle);
StyleConstants.setBold(errorStyle, true);
StyleConstants.setForeground(errorStyle, Color.red);
Style paragraphStyle = doc.addStyle("paragraph", defaultStyle);
StyleConstants.setFontSize(paragraphStyle, StyleConstants.getFontSize(paragraphStyle)+5);
StyleConstants.setForeground(paragraphStyle, Color.gray);
pane.setText("");
if (request != null) {
doc.insertString(doc.getLength(), "Request URL: ", boldStyle);
doc.insertString(doc.getLength(), (String)request.getRequest().get("url")+"\n", defaultStyle);
doc.insertString(doc.getLength(), "Method: ", boldStyle);
doc.insertString(doc.getLength(), (String)request.getRequest().get("method")+"\n", defaultStyle);
JSONObject r = getResponseHeaders();
if (r != null) {
int statusCode = request.getResponseCode();
doc.insertString(doc.getLength(), "Status: ", boldStyle);
String status = (String)r.get("Status");
if (status == null) {
status = statusCode == -1 ? "" : ""+statusCode +
" " + request.getResponse().get("statusText");
}
doc.insertString(doc.getLength(), status+"\n",
statusCode >= 400 ? errorStyle : defaultStyle);
Boolean fromCache = (Boolean)r.get("fromDiskCache");
if (Boolean.TRUE.equals(fromCache)) {
doc.insertString(doc.getLength(), "From Disk Cache: ", boldStyle);
doc.insertString(doc.getLength(), "yes\n", defaultStyle);
}
} else if (request.isFailed()) {
doc.insertString(doc.getLength(), "Status: ", boldStyle);
doc.insertString(doc.getLength(), "Request was cancelled.\n", errorStyle);
}
} else {
doc.insertString(doc.getLength(), "Request URL: ", boldStyle);
doc.insertString(doc.getLength(), wsRequest.getURL()+"\n", defaultStyle);
doc.insertString(doc.getLength(), "Status: ", boldStyle);
if (wsRequest.getErrorMessage() != null) {
doc.insertString(doc.getLength(), wsRequest.getErrorMessage()+"\n", errorStyle);
} else {
doc.insertString(doc.getLength(), wsRequest.isClosed() ? "Closed\n" :
wsRequest.getHandshakeResponse() == null ? "Opening\n" : "Open\n", defaultStyle);
}
}
JSONObject requestHeaders = getRequestHeaders();
if (requestHeaders == null) {
return;
}
doc.insertString(doc.getLength(), "\n", defaultStyle);
doc.insertString(doc.getLength(), "Request Headers\n", paragraphStyle);
printHeaders(pane, requestHeaders, doc, boldStyle, defaultStyle);
if (getResponseHeaders() != null) {
doc.insertString(doc.getLength(), "\n", defaultStyle);
doc.insertString(doc.getLength(), "Response Headers\n", paragraphStyle);
printHeaders(pane, getResponseHeaders(), doc, boldStyle, defaultStyle);
}
}
@Override
public void mouseMoved(MouseEvent e) {
JTextPane pane = (JTextPane)e.getSource();
StyledDocument doc = pane.getStyledDocument();
int offset = pane.viewToModel(e.getPoint());
Element elem = doc.getCharacterElement(offset);
Highlight h = getHighlight(pane, offset);
Highlight prevHighlight = (Highlight) pane.getClientProperty(PREV_HIGHLIGHT_PROPERTY);
AttributeSet prevAs = (AttributeSet) pane.getClientProperty(PREV_HIGHLIGHT_ATTRIBUTES);
// if(h != null && h.equals(prevHighlight)) {
// return; // nothing to do
// } else
if(prevHighlight != null && prevAs != null) {
doc.setCharacterAttributes(prevHighlight.startOffset, prevHighlight.endOffset - prevHighlight.startOffset, prevAs, true);
pane.putClientProperty(PREV_HIGHLIGHT_PROPERTY, null);
pane.putClientProperty(PREV_HIGHLIGHT_ATTRIBUTES, null);
}
int modifiers = e.getModifiers() | e.getModifiersEx();
if ( (modifiers & InputEvent.CTRL_DOWN_MASK) == InputEvent.CTRL_DOWN_MASK ||
(modifiers & InputEvent.META_DOWN_MASK) == InputEvent.META_DOWN_MASK)
{
AttributeSet as = elem.getAttributes();
if (StyleConstants.isUnderline(as)) {
// do not underline whats already underlined
return;
}
Font font = doc.getFont(as);
FontMetrics fontMetrics = pane.getFontMetrics(font);
try {
Rectangle rectangle = new Rectangle(
pane.modelToView(elem.getStartOffset()).x,
pane.modelToView(elem.getStartOffset()).y,
fontMetrics.stringWidth(doc.getText(elem.getStartOffset(), elem.getEndOffset() - elem.getStartOffset())),
fontMetrics.getHeight());
if (h != null && offset < elem.getEndOffset() - 1 && rectangle.contains(e.getPoint())) {
Style hlStyle = doc.getStyle("regularBlue-findtype"); // NOI18N
pane.putClientProperty(PREV_HIGHLIGHT_ATTRIBUTES, as.copyAttributes());
doc.setCharacterAttributes(h.startOffset, h.endOffset - h.startOffset, hlStyle, true);
// doc.setCharacterAttributes(h.startOffset, h.endOffset - h.startOffset, as.copyAttributes(), true);
pane.putClientProperty(PREV_HIGHLIGHT_PROPERTY, h);
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
}
private Element element(MouseEvent e) {
JTextPane pane = (JTextPane)e.getSource();
StyledDocument doc = pane.getStyledDocument();
return doc.getCharacterElement(pane.viewToModel(e.getPoint()));
}
public void constructText(JTextPane pluginInfoArea)
{
Metadata info = plugin.getInfo();
StyledDocument doc = pluginInfoArea.getStyledDocument();
AboutDialog.addStylesToDocument(doc);
AboutDialog.append(doc, "Plugin Name: ", "bold");
AboutDialog.append(doc, info.get("name") + "\n", "regular");
AboutDialog.append(doc, "Author(s): ", "bold");
AboutDialog.append(doc, info.get("authors") + "\n", "regular");
AboutDialog.append(doc, "Current Version: ", "bold");
AboutDialog.append(doc, info.get("version") + "\n", "regular");
AboutDialog.append(doc, "Last Updated: ", "bold");
AboutDialog.append(doc, info.get("updated") + "\n", "regular");
AboutDialog.append(doc, "Location: ", "bold");
AboutDialog.append(doc, info.get("location") + "\n", "regular");
AboutDialog.append(doc, "Compatible with Spade: ", "bold");
if(info.has("min-spade-version"))
{
if(info.has("max-spade-version"))
{
AboutDialog.append(doc, info.get("min-spade-version") + " - " + info.get("max-spade-version"), "regular");
}
else
{
AboutDialog.append(doc, info.get("min-spade-version") + "+", "regular");
}
}
else if(info.has("max-spade-version"))
{
AboutDialog.append(doc, "<" + info.get("max-spade-version"), "regular");
}
else
{
AboutDialog.append(doc, "any", "regular");
}
AboutDialog.append(doc, "\n\nDescription: ", "bold");
AboutDialog.append(doc, info.get("description"), "regular");
}
private void addAuthor (JTextPane pane, RevisionItem item, boolean selected, Collection<SearchHighlight> highlights) throws BadLocationException {
LogEntry entry = item.getUserData();
StyledDocument sd = pane.getStyledDocument();
clearSD(pane, sd);
Style selectedStyle = createSelectedStyle(pane);
Style normalStyle = createNormalStyle(pane);
Style style;
if (selected) {
style = selectedStyle;
} else {
style = normalStyle;
}
Style authorStyle = createAuthorStyle(pane, normalStyle);
Style hiliteStyle = createHiliteStyleStyle(pane, normalStyle, searchHiliteAttrs);
String author = entry.getAuthor();
AuthorLinker l = linkerSupport.getLinker(VCSHyperlinkSupport.AuthorLinker.class, id);
if(l == null) {
VCSKenaiAccessor.KenaiUser kenaiUser = getKenaiUser(author);
if (kenaiUser != null) {
l = new VCSHyperlinkSupport.AuthorLinker(kenaiUser, authorStyle, sd, author);
linkerSupport.add(l, id);
}
}
int pos = sd.getLength();
if(l != null) {
l.insertString(sd, selected ? style : null);
} else {
sd.insertString(sd.getLength(), author, style);
}
if (!selected) {
for (SearchHighlight highlight : highlights) {
if (highlight.getKind() == SearchHighlight.Kind.AUTHOR) {
int doclen = sd.getLength();
String highlightMessage = highlight.getSearchText();
String authorText = sd.getText(pos, doclen - pos).toLowerCase();
int idx = authorText.indexOf(highlightMessage);
if (idx > -1) {
sd.setCharacterAttributes(doclen - authorText.length() + idx, highlightMessage.length(), hiliteStyle, false);
}
}
}
}
}
/**
* Create the frame.
*/
public ReadLogsWindow() {
setTitle("Coder HPMSA - [Read Logs]");
setBounds(100, 100, 660, 550);
setBackground(Color.decode("#066d95"));
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setIconImage(Toolkit.getDefaultToolkit().
getImage(getClass().getResource(LOGOPATH)));
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
getContentPane().add(scrollPane, BorderLayout.CENTER);
editorPane = new JTextPane();
editorPane.setBackground(new Color(255, 255, 240));
editorPane.setFont(new Font("Verdana", Font.PLAIN, 13));
editorPane.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
editorPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
editorPane.setEditable(false);
scrollPane.setViewportView(editorPane);
final JPanel filesPanel = new JPanel();
filesPanel.setPreferredSize(new Dimension(200, 10));
getContentPane().add(filesPanel, BorderLayout.EAST);
filesPanel.setLayout(new BorderLayout(0, 0));
final JScrollPane listScrollPane = new JScrollPane();
listScrollPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
listScrollPane.setViewportView(logFilesList());
filesPanel.add(listScrollPane, BorderLayout.CENTER);
final JPanel titlePanel = new JPanel();
titlePanel.setPreferredSize(new Dimension(10, 40));
titlePanel.setBackground(Color.decode("#066d95"));
titlePanel.setAutoscrolls(true);
getContentPane().add(titlePanel, BorderLayout.NORTH);
titlePanel.setLayout(new BorderLayout(0, 0));
final JLabel lblTitle = new JLabel("SYSTEM LOG RECORDS");
lblTitle.setHorizontalTextPosition(SwingConstants.CENTER);
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setAutoscrolls(true);
lblTitle.setFont(new Font("Verdana", Font.BOLD, 25));
lblTitle.setForeground(UIManager.getColor("Button.highlight"));
titlePanel.add(lblTitle, BorderLayout.CENTER);
final StyledDocument doc = editorPane.getStyledDocument();
final SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
setVisible(true);
}
public static void centerText(JTextPane pane) {
StyledDocument doc = pane.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
}