Java Swing JTextPane

来源:互联网 发布:vim linux c 插件 编辑:程序博客网 时间:2024/05/16 14:08

The JTextPane class is a subclass of the JEditorPane class and is a specialized component to handle the styled document with embedded images and components.

To display an HTML, RTF, or plain document, use the JEditorPane. To edit or display styled text, use the JTextPane. JTextPane is a mini word processor.

A JTextPane uses a styled document, which is an instance of the StyledDocument interface, as its model.

The StyledDocument interface inherits the Document interface. DefaultStyledDocument is an implementation class for the StyledDocument interface.

A JTextPane uses a DefaultStyledDocument as its default model.

A document in a Swing text component contains elements organized in a tree-like structure.

An element in a document is an instance of the javax.swing.text.Element interface.

Styled Text

import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;//from  w w  w.  j  a  v a 2  s. co  mimport javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;import javax.swing.text.StyleConstants;public class Main {  public static void main(String args[]) throws BadLocationException {    JFrame jf = new JFrame("StyledText");    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    Container cp = jf.getContentPane();    JTextPane pane = new JTextPane();    SimpleAttributeSet set = new SimpleAttributeSet();    StyleConstants.setBold(set, true);    // Set the attributes before adding text    pane.setCharacterAttributes(set, true);    pane.setText("java2s.com ");    set = new SimpleAttributeSet();    StyleConstants.setItalic(set, true);    StyleConstants.setForeground(set, Color.red);    StyleConstants.setBackground(set, Color.blue);    Document doc = pane.getStyledDocument();    doc.insertString(doc.getLength(), "Swing ", set);    set = new SimpleAttributeSet();    StyleConstants.setFontSize(set, 24);    doc.insertString(doc.getLength(), "Tutorial", set);    JScrollPane scrollPane = new JScrollPane(pane);    cp.add(scrollPane, BorderLayout.CENTER);    jf.setSize(400, 300);    jf.setVisible(true);  }}
0 0
原创粉丝点击