使用 Java 向 JTextPane 元件插入影像


假設以下是我們具有橙色背景色的 JTextPane −

JTextPane textPane = new JTextPane();
textPane.setBackground(Color.orange);

現在,設定樣式和屬性。此外,設定字型 −

SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
textPane.setCharacterAttributes(attributeSet, true);
textPane.setText("Recall this and ");
Font font = new Font("Verdana", Font.BOLD, 22);
textPane.setFont(font);

在顯示上述文字後,我們將使用 setIcon() 插入影像 −

StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon("E:\kind.png"));
doc.insertString(doc.getLength(), "invisible text", style);

以下是將影像插入到元件中的示例。在此處,我們將影像插入到 JTextPane 元件 −

示例

package my;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import javax.swing.ImageIcon;
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("Recall this and ");
      Font font = new Font("Verdana", Font.BOLD, 22);
      textPane.setFont(font);
      StyledDocument doc2 = (StyledDocument) textPane.getDocument();
      Style style2 = doc2.addStyle("StyleName", null);
      StyleConstants.setIcon(style2, new ImageIcon("E:\kind.png"));
      doc2.insertString(doc2.getLength(), "invisible text", style2);
      JScrollPane scrollPane = new JScrollPane(textPane);
      scrollPane = new JScrollPane(textPane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

輸出

更新於: 2019 年 7 月 30 日

550 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.