如何在 Java 中设置 JTextPane 的样式?

java 8object oriented programmingprogramming更新于 2025/9/2 19:56:17

要设置 JTextPane 中文本的样式,请使用 setItalic() 或 setBold() 分别设置字体的斜体或粗体样式。

以下是我们的 JTextPane 组件 −

JTextPane pane = new JTextPane();

现在,使用 StyleConstants 类为我们上面创建的 JTextPane 设置样式。我们还设置了背景色和前景色 −

SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.black);
StyleConstants.setBackground(attributeSet, Color.orange);
pane.setCharacterAttributes(attributeSet, true);

以下是为 JTextPane 设置样式的示例 −

示例

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class SwingDemo {
   public static void main(String args[]) throws BadLocationException {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container container = frame.getContentPane();
      JTextPane pane = new JTextPane();
      SimpleAttributeSet attributeSet = new SimpleAttributeSet();
      StyleConstants.setItalic(attributeSet, true);
      StyleConstants.setForeground(attributeSet, Color.black);
      StyleConstants.setBackground(attributeSet, Color.orange);
      pane.setCharacterAttributes(attributeSet, true);
      pane.setText("We are learning Java and this is a demo text!");
      JScrollPane scrollPane = new JScrollPane(pane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

输出


相关文章