如何在 JTextPane 中为不同的单词设置前景颜色
要为不同的单词设置前景颜色,请使用 SimpleAttributeSet 和 StyleConstants 类。同时,还使用 StyledDocument 类来设置不同的单词样式。对于不同的单词,请使用 insertString()。
首先,创建一个新的 JTextPane -
At first, create a new JTextPane: JTextPane pane = new JTextPane();
现在,使用这些类为某些单词设置样式和颜色 −
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("", null);
StyleConstants.setForeground(style, Color.red);
StyleConstants.setBackground(style, Color.white);
doc.insertString(doc.getLength(), "Game of Thrones ", style);现在,以不同的方式调整其他一些单词的样式 −
StyleConstants.setForeground(style, Color.yellow); StyleConstants.setBackground(style, Color.gray); doc.insertString(doc.getLength(), "Season 8", style);
以下是一个示例,说明如何在 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.setBackground(Color.orange);
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
textPane.setCharacterAttributes(attributeSet, true);
textPane.setText("We waited long for ");
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(), "Game of Thrones ", style);
StyleConstants.setForeground(style, Color.yellow);
StyleConstants.setBackground(style, Color.gray);
doc.insertString(doc.getLength(), "Season 8", style);
JScrollPane scrollPane = new JScrollPane(textPane);
container.add(scrollPane, BorderLayout.CENTER);
frame.setSize(550, 300);
frame.setVisible(true);
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP