What are the differences between a JTextPane and a JEditorPane in Java?
JTextPane是JEditorPane的扩展,它提供了诸如字体,文本样式,颜色等文字处理功能。如果我们需要进行繁重的文本处理,则可以使用此类,而JEditorPane支持HTML / RTFcontent的显示/编辑,并且可以通过创建我们的扩展来进行扩展。自己的EditorKit。
JTextPane
- JTextPane是JEditorPane的子类。
- JTextPaneis用于具有嵌入式图像和组件的样式化文档。
- JTextPane是一个文本组件,可以用图形表示的属性进行标记,并且可以使用DefaultStyledDocument作为默认模型。
- JTextPane的重要方法是addStyle(),getCharacterAttributes(),getStyledDocument(),setDocument(),setEditorKit(),setStyledDocument()等。
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import java.awt.*; import javax.swing.*; import javax.swing.text.*; public class JTextPaneTest { public static void main(String args[]) throws BadLocationException { JFrame frame = new JFrame("JTextPane Test"); Container cp = frame.getContentPane(); JTextPane pane = new JTextPane(); SimpleAttributeSet set = new SimpleAttributeSet(); StyleConstants.setBold(set, true); pane.setCharacterAttributes(set, true); pane.setText("Welcome to"); set = new SimpleAttributeSet(); StyleConstants.setItalic(set, true); StyleConstants.setForeground(set, Color.blue); Document doc = pane.getStyledDocument(); doc.insertString(doc.getLength()," Tutorials", set); set = new SimpleAttributeSet(); StyleConstants.setFontSize(set, 20); doc.insertString(doc.getLength()," Point", set); JScrollPane scrollPane = new JScrollPane(pane); cp.add(scrollPane, BorderLayout.CENTER); frame.setSize(375, 250); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } } |
输出量
JEdi??torPane
- JEdi??torPane是一种文本区域,可以显示各种文本格式
- 默认情况下,JEditorPane支持HTML和RTF(富文本格式),我们可以构建自己的编辑器工具包来处理特定的内容类型。
- 我们可以使用setContentType()方法选择要显示的文档,并使用setEditorKit()方法为JEditorPaneexplicititly设置自定义编辑器。
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import javax.swing.*; public class JEditorPaneTest extends JFrame { public JEditorPaneTest() { setTitle("JEditorPane Test"); JEditorPane editorPane = new JEditorPane(); editorPane.setContentType("text/html"); editorPane.setText("Java<p><center>[wp_ad_camp_3]</center></p><p> is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. </p>"); setSize(350, 275); setContentPane(editorPane); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] a) { new JEditorPaneTest(); } } |
输出量