將樣式化的文字插入到 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