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

Sid*_*ani 5 java swing highlighting jtextpane

只是试图为JTextPane中的文本着色 - 但问题是文本和下划线不能有不同的颜色.我该怎么办?或者甚至可能吗?下面的示例打印所有文本并以红色下划线.

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);
Run Code Online (Sandbox Code Playgroud)

Sid*_*ani 5

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

使用 AttributeSet 以不同颜色下划线 StyleConstant

这是示例代码的链接

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

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

int y = a.getBounds().y + a.getBounds().height + 2 ; 
Run Code Online (Sandbox Code Playgroud)

它工作正常


mKo*_*bel 2

  • 例如对于 Html

  • Document返回模型以查看,可以确定行开始/结束的索引