如何在 Java 中設定 JTextPane 的樣式?


如要設定 JTextPane 中文字的樣式,請使用 setItalic() 或 setBold(),分別設定字型為斜體或粗體樣式。

以下為我們的 JTextPane 元件 -

JTextPane pane = new JTextPane();

現在,使用 StyleConstants 類設定我們在上面建立的 JTextPane 的樣式。我們還設定了背景色和前景色 -

SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.black);
StyleConstants.setBackground(attributeSet, Color.orange);
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 pane = new JTextPane();
      SimpleAttributeSet attributeSet = new SimpleAttributeSet();
      StyleConstants.setItalic(attributeSet, true);
      StyleConstants.setForeground(attributeSet, Color.black);
      StyleConstants.setBackground(attributeSet, Color.orange);
      pane.setCharacterAttributes(attributeSet, true);
      pane.setText("We are learning Java and this is a demo text!");
      JScrollPane scrollPane = new JScrollPane(pane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

輸出

更新時間: 2019-07-30

837 次瀏覽

開啟你的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.