如何在 Java 中為 JTextPane 文字設定字型、樣式、大小和顏色


對於 JTextPane 的背景色和前景色,請使用以下程式碼——

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

對於字型、樣式和大小,請使用 Font 類並設定字型——

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

以下是在 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.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);
   }
}

輸出

更新於: 30-Jul-2019

1K+ 瀏覽量

開始你的 職業

透過完成課程獲得認證

開始
廣告