基本上你需要创建 3 个类:
您需要扩展javax.swing.text.LabelView以执行您希望的修改视图(无论是否添加彩色下划线)。您将覆盖该paint(Graphics, Shape)
方法。您可以在被覆盖的类中使用此行访问属性 - 属性应该是对文本执行其他操作(如添加下划线)的触发器。
getElement().getAttributes().getAttribute("attribute name");
您需要创建一个新的ViewFactory并覆盖该create
方法。重要的是,在执行此操作时要处理所有元素类型(否则内容将无法正确显示。
您需要创建一个StyledEditorKit来告诉窗格ViewFactory
使用哪个。
这是一个简化且可运行的示例:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicTextPaneUI;
import javax.swing.text.*;
public class TempProject extends JPanel{
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
//Adding pane
JTextPane pane = new JTextPane();
pane.setEditorKit(new CustomEditorKit());
pane.setText("Underline With Different Color");
//Set Style
StyledDocument doc = (StyledDocument)pane.getDocument();
MutableAttributeSet attrs = new SimpleAttributeSet();
attrs.addAttribute("Underline-Color", Color.red);
doc.setCharacterAttributes(0, doc.getLength()-1, attrs, true);
JScrollPane sp = new JScrollPane(pane);
frame.setContentPane(sp);
frame.setPreferredSize(new Dimension(400, 300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class CustomEditorKit extends StyledEditorKit{
public ViewFactory getViewFactory(){
return new CustomUI();
}
}
public static class CustomUI extends BasicTextPaneUI{
@Override
public View create(Element elem){
View result = null;
String kind = elem.getName();
if(kind != null){
if(kind.equals(AbstractDocument.ContentElementName)){
result = new MyLabelView(elem);
} else if(kind.equals(AbstractDocument.ParagraphElementName)){
result = new ParagraphView(elem);
}else if(kind.equals(AbstractDocument.SectionElementName)){
result = new BoxView(elem, View.Y_AXIS);
}else if(kind.equals(StyleConstants.ComponentElementName)){
result = new ComponentView(elem);
}else if(kind.equals(StyleConstants.IconElementName)){
result = new IconView(elem);
} else{
result = new LabelView(elem);
}
}else{
result = super.create(elem);
}
return result;
}
}
public static class MyLabelView extends LabelView{
public MyLabelView(Element arg0) {
super(arg0);
}
public void paint(Graphics g, Shape a){
super.paint(g, a);
//Do whatever other painting here;
Color c = (Color)getElement().getAttributes().getAttribute("Underline-Color");
if(c != null){
int y = a.getBounds().y + (int)getGlyphPainter().getAscent(this);
int x1 = a.getBounds().x;
int x2 = a.getBounds().width + x1;
g.setColor(c);
g.drawLine(x1, y, x2, y);
}
}
}
}
这是另一个示例代码的链接:
http://java-sl.com/tip_colored_strikethrough.html
这个答案主要是为了后代,我认为添加链接代码和解释的简化版本将有助于使事情更容易理解。