如何获取 jTextPane 中特定字符的字体(isBold、isUnderline)?

How can I get the font(isBold,isUnderline) of a specific character in jTextPane?

我用过

doc.setCharacterAttributes(textPane.getSelectionStart(),
           textPane.getSelectionEnd()-textPane.getSelectionStart(),red, false);

更改JTextpane 中文本的显示样式。 我尝试使用函数 getCharacterAttributes() 查看特定文本的样式是什么,但是 DefaultStyledModel 没有这样的方法。 我能用它做什么?

加分:

我知道在vb.net中,一个richtextbox有一个叫做"rtftext"之类的属性,它包含了richtextbox中的文本和字体信息。 JavaJTextPane中类似method/attribute的是什么?我尝试了 getDocument()setDocument 但没有任何反应。

您是否尝试过将文本设置为 HTML?我相信 JTextPane 支持 HTML,因此请尝试将您的文本设置为:

myTextPane.setText("<html>This text box has <b>bold text</b> in it!</html>");

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class SimpleAttributeBoldItalic {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Simple Attributes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    StyledDocument document = new DefaultStyledDocument();

    SimpleAttributeSet attributes = new SimpleAttributeSet();
    attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
    attributes.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);

    try {
      document.insertString(document.getLength(), "Bold, Italic", attributes);
    } catch (BadLocationException badLocationException) {
      System.err.println("Bad insert");
    }

     JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);

    frame.add(scrollPane, BorderLayout.CENTER);

    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}

Font boldFont=new Font(textArea.getFont().getName(), Font.BOLD, textArea.getFont().getSize());
      textArea.setFont(boldFont); // bold text 

由于您使用的是 JTextPane,因此您应该使用 SimpleAttributeSet:

SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setUnderline(attributeSet, true);
jta.getStyledDocument().setCharacterAttributes(0, jta.getText().length(),
    attributeSet, false); 

就是这样。

GET the attribute

您也许可以使用 StyledDocument#getCharacterElement(int) and Element#getAttributes()

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class CharacterAttributesTest {
  public Component makeUI() {
    StyleContext style = new StyleContext();
    StyledDocument doc = new DefaultStyledDocument(style);
    try {
      doc.insertString(0, "abcdefghijklmnopqrstuvwxyz", null);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
    MutableAttributeSet attr1 = new SimpleAttributeSet();
    attr1.addAttribute(StyleConstants.Bold, Boolean.TRUE);
    attr1.addAttribute(StyleConstants.Foreground, Color.RED);
    doc.setCharacterAttributes(5, 8, attr1, false);

    MutableAttributeSet attr2 = new SimpleAttributeSet();
    attr2.addAttribute(StyleConstants.Underline, Boolean.TRUE);
    doc.setCharacterAttributes(3, 20, attr2, false);

    JTextPane textPane = new JTextPane(doc);
    textPane.addCaretListener(e -> {
      if (e.getDot() == e.getMark()) {
        AttributeSet a = doc.getCharacterElement(e.getDot()).getAttributes();
        System.out.println("isBold: " + StyleConstants.isBold(a));
        System.out.println("isUnderline: " + StyleConstants.isUnderline(a));
        System.out.println("Font: " + style.getFont(a));
        System.out.println("Foreground: " + StyleConstants.getForeground(a));
      }
    });

    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(textPane));
    return p;
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new CharacterAttributesTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

您可以使用下面的代码从 JTextpane 中的选定文本中获取样式。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.text.AttributeSet;
import javax.swing.*;
import javax.swing.text.*;

 public class TesxtPane {

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            JFrame frame = new TextStyleTestFrame();
            frame.setSize(300, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
 }
}
class TextStyleTestFrame extends JFrame {
private JButton btnStyle = new JButton("Bold");
private JTextPane textPane = new JTextPane();

public TextStyleTestFrame() {
    super("TextPaneStyle Test");
    textPane.setText("Smaple String");
    this.add(textPane, BorderLayout.CENTER);
    JPanel panel = new JPanel();
    panel.add(btnStyle);
    this.add(panel, BorderLayout.NORTH);
    btnStyle.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            changeStyle();
        }
    });
}


private void changeStyle() {

    //get selected text style
    int start = textPane.getSelectionStart();
    int end = textPane.getSelectionEnd();

    if (start == end) {
        return;
    }
    StyledDocument doc = (StyledDocument) textPane.getDocument();
    Element element = doc.getCharacterElement(start);
    AttributeSet as = element.getAttributes();
    //apply a new style based on previous 
    MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
    StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
    doc.setCharacterAttributes(start, textPane.getSelectedText().length(), asNew, true);
    String text = (StyleConstants.isBold(as) ? "Cancel Bold" : "Bold");
    btnStyle.setText(text);
    boolean isBold = StyleConstants.isBold(as) ? false : true;
    boolean isItalic = StyleConstants.isItalic(as);
    System.out.println("selected value is isItalic?" + isItalic);
    System.out.println("selected value is isBold?" + isBold);
   }