如何在JTextPane中为文本和下划线设置不同的颜色?

问题描述:

一直在尝试为JTextPane中的文本着色-但问题是文本和下划线不能具有不同的颜色.我应该怎么做,或者甚至有可能?下面的示例以红色打印所有文本和下划线.

Just been trying to color the text in JTextPane - but the issue is cannot have different colors for text and the underline. How should I do that or is that even possible? The example below prints all the text and underline in RED.

JTextPane pane = new JTextPane();

StyleContext context = new StyleContext();

Style style = pane.addStyle("Black", null);
StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.BLACK);

StyledDocument document = pane.getStyledDocument();


style = pane.addStyle("Red Underline", style);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setUnderline(style, true);

pane.getDocument().insertString(0,  "Test String", style);

这是我找到的解决方案...

Here's the solution I found...

下划线StyleConstant具有AttributeSet的不同颜色

这是示例代码的链接

http://java-sl.com/tip_colored_strikethrough.html

只需更改以下行即可解决...

just changing the following line solves it ...

int y = a.getBounds().y + a.getBounds().height + 2 ; 

效果很好