问题描述
大家好,我有一个面板,我在其中使用了 JTextPane,我想交替使用文本和下划线文本,但我不知道为什么我不能在要下划线的文本部分下划线。 这是我的代码,我只想在文本下划线:“下划线”:
public class TestMLD extends JPanel{
private MLD mld;
TestMLD() throws BadLocationException{
init();
}
private void init() throws BadLocationException {
JTextPane textPane = new JTextPane();
textPane.setopaque(false);
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet,true);
textPane.setCharacterattributes(attributeSet,true);
Font font = new Font("Serif",Font.ITALIC,18);
textPane.setFont(font);
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("",null);
doc.insertString(doc.getLength(),"Some text ",style);
StyleConstants.setUnderline(attributeSet,true);
/**THE PART I WANT TO UNDERLINE **/
doc.insertString(doc.getLength(),"Underline ",style);
StyleConstants.setUnderline(attributeSet,false);
doc.insertString(doc.getLength(),"Some text\n",style);
JScrollPane scrollPane = new JScrollPane(textPane);
textPane.setEditable(false);
add(textPane);
}
public static void main(String[] args) throws BadLocationException {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}
提前致谢
解决方法
StyleConstants.setUnderline(attributeSet,true);
您正在为“attributeSet”设置“下划线”属性。
doc.insertString(doc.getLength(),"Underline ",style);
您为什么要尝试使用“样式”。您的“样式”变量没有属性。
使用“attributeSet”,因为它包含您的属性:
//doc.insertString(doc.getLength(),style);
doc.insertString(doc.getLength(),attributeSet);
另外,你为什么要设置“斜体”属性:
StyleConstants.setItalic(attributeSet,true);
textPane.setCharacterAttributes(attributeSet,true);
Font font = new Font("Serif",Font.ITALIC,18);
您使用的是“斜体”字体。
摆脱:
//StyleConstants.setItalic(attributeSet,true);
//textPane.setCharacterAttributes(attributeSet,true);