如何在Java中为JTextPane文本设置字体,样式,大小和颜色

How to set font face, style, size and color for JTextPane text in Java

对于JTextPane的背景色和前景色,请使用以下命令-

1
2
3
JTextPane textPane = new JTextPane();
textPane.setBackground(Color.blue);
textPane.setBackground(Color.green);

对于字体,样式和大小,请使用Font类并设置字体-

1
2
Font font = new Font("Serif", Font.ITALIC, 18);
textPane.setFont(font);

以下是在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
29
30
31
32
33
34
35
36
37
38
39
40
41
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
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.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
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 textPane = new JTextPane();
   textPane.setBackground(Color.blue);
   textPane.setBackground(Color.green);
   SimpleAttributeSet attributeSet = new SimpleAttributeSet();
   StyleConstants.setItalic(attributeSet, true);
   textPane.setCharacterAttributes(attributeSet, true);
   textPane.setText("World Cup Cricket begins from");
   Font font = new Font("Serif", Font.ITALIC, 18);
   textPane.setFont(font);
   StyledDocument doc = textPane.getStyledDocument();
   Style style = textPane.addStyle("", null);
   StyleConstants.setForeground(style, Color.red);
   StyleConstants.setBackground(style, Color.white);
   doc.insertString(doc.getLength(),"30th May", style);
   StyleConstants.setForeground(style, Color.yellow);
   StyleConstants.setBackground(style, Color.gray);
   doc.insertString(doc.getLength(),"2019", style);
   JScrollPane scrollPane = new JScrollPane(textPane);
   container.add(scrollPane, BorderLayout.CENTER);
   frame.setSize(550, 300);
   frame.setVisible(true);
 }
}

输出量