⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 generaltext.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<code>PlainDocument</code> provides a basic container for textwhere all the text is displayed in the same font.Even though an editor pane is a styled text component,it uses an instance of <code>PlainDocument</code> by default.The default document for astandard <code>JTextPane</code> in an instance of<code>DefaultStyledDocument</code> &#151;a containerfor styled text in no particular format.However,the document instance used by any particular editor paneor text pane depends on the type of content bound to it.If you use <code>setPage</code>to load text into an editor pane or text pane,the document instance used by the pane might change.Refer to<a href="editorpane.html">How to Use Editor Panes and Text Panes</a>for details.<p>Although you can set the document of a text component,it's usually easier to let it be set automatically,and use a <em>document filter</em> if necessaryto change how the text component's data is set.You can implement certain customizationseither by installing a document filteror by replacing a text component's documentwith one of your own,For example,the text pane in <code>TextComponentDemo</code>has a document filter thatlimits the number of characters the text pane can contain.</blockquote><a name="filter"><h3>Implementing a Document Filter</h3></a><blockquote>To implement a document filter,you create a subclass of <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DocumentFilter.html"><code>DocumentFilter</code></a> and then attach it to a document using the<code>setFilter</code> method defined in<code>AbstractDocument</code>.Although it's possible to havedocuments that don't descend from <code>AbstractDocument</code>,by default Swing text components use<code>AbstractDocument</code> subclasses for their documents.<p>The <code>TextComponentDemo</code> application has a document filter,<a class="SourceLink" target="_blank" href="examples/DocumentSizeFilter.java"><code>DocumentSizeFilter</code></a>,that limits the number of characters that the text pane can contain.Here's the code that creates the filterand attaches it to the text pane's document:<blockquote><pre><em>...//Where member variables are declared:</em>JTextPane textPane;AbstractDocument doc;static final int MAX_CHARACTERS = 300;...textPane = new JTextPane();...StyledDocument styledDoc = textPane.getStyledDocument();if (styledDoc instanceof AbstractDocument) {    doc = (AbstractDocument)styledDoc;    doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));} </pre></blockquote>To limit the characters allowed in the document,<code>DocumentSizeFilter</code> overrides <code>DocumentFilter</code>'s<code>insertString</code> method, whichis called each time text is inserted into the document.It also overrides the <code>replace</code> method,which is most likely to be called when the user changes textby pasting it in.In general, text insertion can be the result ofthe user typing or pasting text in,or because of a call to <code>setText</code>.Here is <code>DocumentSizeFilter</code>'simplementation of <code>insertString</code>:<blockquote><pre>public void insertString(FilterBypass fb, int offs,                         String str, AttributeSet a)    throws BadLocationException {    if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)        super.insertString(fb, offs, str, a);    else        Toolkit.getDefaultToolkit().beep();}</pre></blockquote><p>The code for <code>replace</code> is similar. The<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DocumentFilter.FilterBypass.html"><code>FilterBypass</code></a> parameter to the methods defined by <code>DocumentFilter</code>is simply an object that enables updating the documentin a thread-safe way.<p>Because the preceding document filteris only concerned about additions to the document's data,it only overrides the <code>insertString</code>and <code>replace</code> methods.Most document filters would override <code>DocumentFilter</code>'s <code>remove</code> method, as well.</blockquote><a name="doclisteners"><h3>Listening for Changes on a Document</h3></a><blockquote>You can register two different types of listeners ona document: document listeners and undoable edit listeners.This subsection covers document listeners.For information about undoable edit listeners,refer to <a href="#undo">Implementing Undo and Redo</a>.<p>A document notifies registered document listenersof changes to the document.Use a document listener to reactwhen text is inserted or removed from a document,or when the style of some of the text changes.<p>The <code>TextComponentDemo</code> program uses a documentlistener to update the change log whenever a change is madeto the text pane. The following line of code registers an instance of<code>MyDocumentListener</code> as a listener on thetext pane's document:<blockquote><pre>doc.addDocumentListener(new MyDocumentListener());</pre></blockquote>Here's the implementation of <code>MyDocumentListener</code>:<blockquote><pre>protected class MyDocumentListener implements DocumentListener {    public void insertUpdate(DocumentEvent e) {        displayEditInfo(e);    }    public void removeUpdate(DocumentEvent e) {        displayEditInfo(e);    }    public void changedUpdate(DocumentEvent e) {        displayEditInfo(e);    }    private void displayEditInfo(DocumentEvent e) {            Document document = (Document)e.getDocument();            int changeLength = e.getLength();            changeLog.append(e.getType().toString() + ": "                + changeLength + " character"                + ((changeLength == 1) ? ". " : "s. ")                + " Text length = " + document.getLength()                + "." + newline);    }} </pre></blockquote>The listener implements three methods for handlingthree different types of document events:insertion, removal, and style changes.<code>StyledDocument</code>s can fire all three types of events.<code>PlainDocument</code>s fire events only for insertion and removal.For general information about document listenersand document events,see<a href="../events/documentlistener.html">How to Write a Document Listener</a>.<p><a name="dontdothis"></a>Remember that the document filter for this text pane limitsthe number of characters allowed in the document.If you try to add more text than the document filter allows,the document filter blocks the change and the listener's<code>insertUpdate</code> method is not called.Document listeners are notified of changes only ifthe change has already occurred.<p>Sometimes, you might be tempted to change thedocument's text from within a document listener.<strong> However, you should never modify the contents ofa text component from within a document listener.</strong>In fact, if you do, your program will likely deadlock!Instead, you can use a formatted text fieldor provide a document filter.</blockquote><a name="caret"><h3>Listening for Caret and Selection Changes</h3></a> <blockquote> The <code>TextComponentDemo</code> program usesa caret listener to displaythe current position of the caret or,if text is selected,the extent of the selection.<p>The caret listener class in this example is a <code>JLabel</code> subclass.Here's the code that creates the caret listener labeland makes it a caret listener of the text pane:<blockquote><pre>//Create the status areaCaretListenerLabel caretListenerLabel = new CaretListenerLabel(						"Caret Status");...textPane.addCaretListener(caretListenerLabel);</pre></blockquote>A caret listener must implement one method, <code>caretUpdate</code>,which is called each time the caret moves or the selection changes.Here's the <code>CaretListenerLabel</code>implementation of <code>caretUpdate</code>:<blockquote><pre>public void caretUpdate(CaretEvent e) {    //Get the location in the text    int dot = e.getDot();    int mark = e.getMark();    if (dot == mark) {  // no selection        try {            Rectangle caretCoords = textPane.modelToView(dot);            //Convert it to view coordinates            setText("caret: text position: " + dot +                    ", view location = [" +                    caretCoords.x + ", " + caretCoords.y + "]" +                    newline);        } catch (BadLocationException ble) {            setText("caret: text position: " + dot + newline);        }     } else if (dot < mark) {        setText("selection from: " + dot + " to " + mark + newline);     } else {        setText("selection from: " + mark + " to " + dot + newline);     }}</pre></blockquote>As you can see, this listener updates its text labelto reflect the current state of the caret or selection.The listener gets the information to display from thecaret event object.For general information about caret listenersand caret events,see<a href="../events/caretlistener.html">How to Write a Caret Listener</a>.<p>As with document listeners, a caret listener is passive.It reacts to changes in the caret or in the selection butdoes not change the caret or the selection.If you want to change the caret or selection,then you should use a <em>navigation filter</em>or a custom caret instead.<p>Implementing a navigation filter is similar to implementing a document filter.First, you write a subclass of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/NavigationFilter.html"><code>NavigationFilter</code></a>. You then attach an instance of it to a text component with the<code>setNavigationFilter</code> method.<p>You might create a custom caretto customize the appearance of a caret.To create a caret,write a class that implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/Caret.html"><code>Caret</code></a> interface &#151;perhaps by extending the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DefaultCaret.html"><code>DefaultCaret</code></a> class.Then provide an instance of your class as an argumentto <code>setCaret</code> on a text component.</blockquote><a name="editorkits"><h3>Concepts: About Editor Kits</h3></a><blockquote><p>Under the hood,text components use an <code>EditorKit</code>to tie the various pieces of the text component together.It provides the view factory, document, caret, and actions.An editor kit also reads and writes documents ofa particular format.Although all text components use editor kits,some components hide theirs.You can't set or get the editor kit used bya text field or text area.Editor panes and text panes provide the<code>getEditorKit</code> method to get the current editor kitand the <code>setEditorKit</code> method to change it.<p>For all components,<code>JTextComponent</code> providesAPI for you to indirectly invokeor customize some editor kit capabilities.For example, <code>JTextComponent</code> provides<code>read</code> and <code>write</code> methods,which invoke the editor kit's <code>read</code> and<code>write</code> methods.<code>JTextComponent</code> also providesa method, <code>getActions</code>,which returns all of the actions supported by a component.<p>The Swing text package provides these editor kits:<dl><dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DefaultEditorKit.html"><code>DefaultEditorKit</code></a><dd> Reads and writes plain text,     and provides a basic set of editing commands.     Details of how the text system treats newlines     are in the <code>DefaultEditorKit</code> API documentation.     (To summarize: The '\n' character is used internally,     but the document or platform line separators are used     when writing files.)     All the other editor kits are descendants of      <code>DefaultEditorKit</code>.<dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/StyledEditorKit.html"><code>StyledEditorKit</code></a><dd> Reads and writes styled text, and     provides a minimal set of actions for styled text.     This class is a subclass of <code>DefaultEditorKit</code>     and is the editor kit used by <code>JTextPane</code>     by default.<dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/html/HTMLEditorKit.html"><code>HTMLEditorKit</code></a><dd>Reads, writes, and edits HTML. This is a subclass of    <code>StyledEditorKit</code>.</dl>Each of the editor kits above has been registeredwith the <code>JEditorPane</code>class and associated with the text formatthat the kit reads, writes, and edits.When a file is loaded into an editor pane,the pane checks the format of the file against itsregistered kits.If a registered kit is found that supportsthat file format, the pane uses the kit to read thefile, display, and edit it.Thus, the editor pane effectively transformsitself into an editor for that text format.You can extend <code>JEditorPane</code>to support your own text format by creatingan editor kit for it, and then using<code>JEditorPane</code>'s <code>registerEditorKitForContentType</code>to associate your kit with your text format.</blockquote>        </blockquote>        <div class=NavBit>            <a target=_top href=text.html>&laquo; Previous</a>            &bull;            <a target=_top href=../TOC.html>Trail</a>            &bull;            <a target=_top href=textapi.html>Next &raquo;</a>        </div>    </div>    <div id=Footer><div id=TagNotes>    Problems with the examples? Try <a target="_blank"        href=../../information/run-examples.html>Compiling and Running        the Examples: FAQs</a>.    <br>    Complaints? Compliments? Suggestions? <a target="_blank"        href="http://developer.sun.com/contact/tutorial_feedback.jsp">Give    us your feedback</a>.<br><br>    <a target="_blank" href="../../information/copyright.html">Copyright</a>    1995-2006 Sun Microsystems, Inc.  All rights reserved.    <span id=Download></span></div>     </div>    <div class=PrintHeaders>        <b>Previous page:</b> Using Text Components        <br><b>Next page:</b> The Text Component API    </div>    </body></html> 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -