使用 jTextPane 在文本下划线

问题描述

大家好,我有一个面板,我在其中使用了 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);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...