Documentation

The Java™ Tutorials
Hide TOC
How to Use Editor Panes and Text Panes如何使用编辑器窗格和文本窗格
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Editor Panes and Text Panes如何使用编辑器窗格和文本窗格

Two Swing classes support styled text: JEditorPane and its subclass JTextPane. 两个Swing类支持样式化文本:JEditorPane及其子类JTextPaneThe JEditorPane class is the foundation for Swing's styled text components and provides a mechanism through which you can add support for custom text formats. JEditorPane类是Swing样式化文本组件的基础,并提供了一种机制,通过该机制可以添加对自定义文本格式的支持。If you want unstyled text, use a text area instead.如果需要未设置样式的文本,请使用文本区域

You can see an editor pane and a text pane in use by running TextSamplerDemo. 通过运行TextSamplerDemo,您可以看到正在使用的编辑器窗格和文本窗格。Here is a picture of the TextSamplerDemo example.下面是TextSamplerDemo示例的图片。

An application that provides a sample of each Swing text component

Click the Launch button to run TextSamplerDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行TextSamplerDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the TextSamplerDemo Application

The TextSamplerDemo example barely begins to demonstrate the capabilities of editor panes and text panes. TextSamplerDemo示例刚刚开始演示编辑器窗格和文本窗格的功能。However, the top right editor pane illustrates a handy, easy-to-use feature: it displays uneditable help information loaded from a URL. 然而,右上角的编辑器窗格展示了一个方便易用的功能:它显示从URL加载的不可编辑的帮助信息。The text pane at the lower right demonstrates that you can easily embed images and even components directly into text panes.右下角的文本窗格表明,您可以轻松地将图像甚至组件直接嵌入到文本窗格中。


Note: 

If you need a fully-fledged help system, take a look at the javahelp project.如果您需要一个成熟的帮助系统,请查看javahelp项目。


The Swing text API is powerful and immense, and we could devote an entire book just to using editor panes and text panes. Swing text API功能强大,功能强大,我们可以花一整本书来讨论如何使用编辑器窗格和文本窗格。This section introduces their capabilities, offers hints on which one you might want to use, and points to other sources of information.本节介绍了它们的功能,提供了您可能希望使用哪种功能的提示,并指出了其他信息来源。

Using an Editor Pane to Display Text From a URL使用编辑器窗格显示URL中的文本

One task that you can accomplish without knowing anything about the Swing text system is displaying text from a URL. 您可以在不了解Swing文本系统的情况下完成的一项任务是显示URL中的文本。Here is the code from TextSamplerDemo.java that creates an uneditable editor pane that displays text formatted with HTML tags.下面是TextSamplerDemo.java中的代码,该代码创建了一个不可编辑的编辑器窗格,该窗格显示用HTML标记格式化的文本。

JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
java.net.URL helpURL = TextSamplerDemo.class.getResource(
                                "TextSamplerDemoHelp.html");
if (helpURL != null) {
    try {
        editorPane.setPage(helpURL);
    } catch (IOException e) {
        System.err.println("Attempted to read a bad URL: " + helpURL);
    }
} else {
    System.err.println("Couldn't find file: TextSamplerDemoHelp.html");
}

//Put the editor pane in a scroll pane.
JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
editorScrollPane.setPreferredSize(new Dimension(250, 145));
editorScrollPane.setMinimumSize(new Dimension(10, 10));

The code uses the default constructor to create the editor pane, then calls setEditable(false) so the user cannot edit the text. 代码使用默认构造函数创建编辑器窗格,然后调用setEditable(false),因此用户无法编辑文本。Next, the code creates the URL object, and calls the setPage method with it.接下来,代码创建URL对象,并使用它调用setPage方法。

The setPage method opens the resource pointed to by the URL and figures out the format of the text (which is HTML in the example). setPage方法打开URL指向的资源,并计算文本的格式(在本例中为HTML)。If the text format is known, the editor pane initializes itself with the text found at the URL. 如果文本格式已知,则编辑器窗格将使用URL中的文本进行初始化。A standard editor pane can understand plain text, HTML, and RTF. 标准编辑器窗格可以理解纯文本、HTML和RTF。Note that the page might be loaded asynchronously, which keeps the GUI responsive but means that you should not count on the data being completely loaded after the call to setPage returns.请注意,页面可能是异步加载的,这会使GUI保持响应,但这意味着您不应指望在调用setPage返回后完全加载数据。

Editor Panes vs. Text Panes编辑器窗格与文本窗格

In order to use editor panes and text panes, you need to understand the text system, which is described in Text Component Features. 为了使用编辑器窗格和文本窗格,您需要了解文本系统,这在文本组件功能中有描述。Several facts about editor panes and text panes are scattered throughout that section. 关于编辑器窗格和文本窗格的几个事实分散在该部分中。Here we list the facts again and provide a bit more detail. 这里我们再次列出事实,并提供更多细节。The information here should help you understand the differences between editor panes and text panes, and when to use which.此处的信息将帮助您理解编辑器窗格和文本窗格之间的区别,以及何时使用它们。

An Example of Using a Text Pane使用文本窗格的示例

Here is the code from the TextSamplerDemo example that creates and initializes a text pane.下面是TextSamplerDemo示例中创建和初始化文本窗格的代码。

String[] initString =
        { /* ...  fill array with initial text ... */ };

String[] initStyles =
        { /* ...  fill array with names of styles ... */ };

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
addStylesToDocument(doc);

//Load the text pane with styled text.
try {
    for (int i=0; i < initString.length; i++) {
        doc.insertString(doc.getLength(), initString[i],
                         doc.getStyle(initStyles[i]));
    }
} catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
}

Briefly, this code hard-codes the initial text into an array and creates and hard-codes several styles — objects that represent different paragraph and character formats — into another array. 简而言之,该代码将初始文本硬编码为数组,并创建和硬编码几种样式;表示不同段落和字符格式的对象;进入另一个数组。Next, the code loops over the arrays, inserts the text into the text pane, and specifies the style to use for the inserted text.接下来,代码在数组上循环,将文本插入文本窗格,并指定用于插入文本的样式。

Although this is an interesting example that concisely demonstrates several features of JTextPane, "real-world" programs aren't likely to initialize a text pane this way. 尽管这是一个有趣的示例,简要地展示了JTextPane的几个功能,“现实世界”程序不太可能以这种方式初始化文本窗格。Instead, a program would use an editor pane to save a document which would then be used to initialize the text pane.相反,程序将使用编辑器窗格来保存文档,然后该文档将用于初始化文本窗格。

The Editor Pane and Text Pane API编辑器窗格和文本窗格API

This section lists some of the API related to text and editor panes. 本节列出了一些与文本和编辑器窗格相关的API。Many of the most useful methods for JEditorPane and its subclass JTextPane are inherited from the JTextComponent class. JEditorPane及其子类JTextPane的许多最有用的方法都是从JTextComponent类继承的。You can find the API tables for JTextComponent in The Text Component API. 您可以在文本组件API中找到JTextComponent的API表。Also see The JComponent Class, which describes the API inherited from JComponent.另请参见JComponent,它描述了从jComponent继承的API。

JEditorPane API for Displaying Text from a URL用于显示URL中文本的JEditorPane API
Method or Constructor方法或构造函数 Description描述
JEditorPane(URL)
JEditorPane(String)
Creates an editor pane loaded with the text at the specified URL.创建在指定URL处加载文本的编辑器窗格。
setPage(URL)
setPage(String)
Loads an editor pane (or text pane) with the text at the specified URL.加载带有指定URL处文本的编辑器窗格(或文本窗格)。
URL getPage() Gets the URL for the editor pane's (or text pane's) current page.获取编辑器窗格(或文本窗格)当前页面的URL。
JTextPane API
Method or Constructor方法或构造函数 Description描述
JTextPane()
JTextPane(StyledDocument)
Creates a text pane. 创建文本窗格。The optional argument specifies the text pane's model.可选参数指定文本窗格的模型。
StyledDocument getStyledDocument
setStyledDocument(StyledDocument)
Gets or sets the text pane's model.获取或设置文本窗格的模型。

Examples That Use Text Panes and Editor Panes使用文本窗格和编辑器窗格的示例

To begin using text, you might want to run these programs and examine their code to find something similar to what you want to do.要开始使用文本,您可能需要运行这些程序并检查它们的代码,以找到与您想要做的类似的内容。

Example示例 Where Described描述位置 Notes备注
TextSamplerDemo Using Text Components使用文本组件 Uses each Swing text component.使用每个Swing文本组件。
TextComponentDemo Text Component Features文本组件特征 Provides a customized text pane. 提供自定义文本窗格。Illustrates many text component features, such as undo and redo, document filters, document listeners, caret change listeners, and how to associate editing actions with menus and key strokes.说明了许多文本组件功能,如撤消和重做、文档筛选器、文档侦听器、插入符号更改侦听器,以及如何将编辑操作与菜单和按键笔划关联。
TreeDemo How to Use Trees如何使用树木 Uses an editor pane to display help loaded from an HTML file.使用编辑器窗格显示从HTML文件加载的帮助。

Learn to edit HTML text in JavaFX with the Using JavaFX UI Controls: HTML Editor tutorial.学习使用JavaFXUI控件:HTML编辑器教程在JavaFX中编辑HTML文本。


Previous page: How to Make Dialogs
Next page: How to Use File Choosers