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

How to set style for JTextPane in Java?

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

以下是我们的JTextPane组件-

1
JTextPane pane = new JTextPane();

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

1
2
3
4
5
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.black);
StyleConstants.setBackground(attributeSet, Color.orange);
pane.setCharacterAttributes(attributeSet, true);

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
 }
}

输出量