如何在 Java 中為 JTextPane 設定預設背景色?
若要設定 JTextPane 的預設背景色,請使用 SimpleAttributeSet 和 StyleConstants 類。首先,建立一個新的 JTextPane –
JTextPane pane = new JTextPane();
現在,使用這些類設定樣式和顏色 –
SimpleAttributeSet attributeSet = new SimpleAttributeSet(); StyleConstants.setBackground(attributeSet, Color.white);
現在,將該設定應用於該面板 –
pane.setCharacterAttributes(attributeSet, true);
以下是如何為 JTextPane 設定預設背景色的示例 –
示例
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 textPane = new JTextPane();
textPane.setBackground(Color.cyan);
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.blue);
StyleConstants.setBackground(attributeSet, Color.white);
textPane.setCharacterAttributes(attributeSet, true);
textPane.setText("Updated the background color of the text pane.");
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