将样式化的文本插入到 JTextPane 组件中
使用 SimpleAttributeSet 和 StyleConstants 类在 JTextPane 组件中插入样式化的文本。为此,我们还将使用 StyledDocument。
以下是为 JTextPane 组件插入文本的示例 −
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.setForeground(Color.blue);
textPane.setBackground(Color.cyan);
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setItalic(set, true);
textPane.setCharacterAttributes(set, true);
textPane.setText("This is our text pane! ");
Font font = new Font("Verdana", Font.BOLD, 18);
textPane.setFont(font);
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setBold(style, true);
doc.insertString(doc.getLength(), "Demo text", style);
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane = new JScrollPane(textPane);
container.add(scrollPane, BorderLayout.CENTER);
frame.setSize(550, 300);
frame.setVisible(true);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP