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

📄 generaltext.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 3 页
字号:
     It's important to note, though,     that the menu operates on both text components.<li> Use the items in the <strong>Style</strong> menu     to apply different styles to the text in the text pane.</ol><hr></blockquote>Using this example application as a reference point,this section covers these topics:<ul><li> <a href="#commands">Associating Text Actions with Menus and Buttons</a><li> <a href="#bindingkeystrokes">Associating Text Actions with Key Strokes</a><li> <a href="#undo">Implementing Undo and Redo</a><li> <a href="#document">Concepts: About Documents</a><li> <a href="#filter">Implementing a Document Filter</a><li> <a href="#doclisteners">Listening for Changes on a Document</a><li> <a href="#caret">Listening for Caret and Selection Changes</a><li> <a href="#editorkits">Concepts: About Editor Kits</a></ul></blockquote><a name="commands"><h3>Associating Text Actions with Menus and Buttons</h3></a> <blockquote> All Swing text components supports standardediting commands such as cut, copy, paste, andinserting characters.Each editing command is represented and implemented by an<code>Action</code></a> object.(You can learn about actions by reading <a class="TutorialLink" target="_top" href="../misc/action.html">How to Use Actions</a>.)Actions makes it easy for you to associate a commandwith a GUI component, such as a menu item or button,and therefore build a GUI around a text component.<p>You can invoke the <code>getActions</code> method on anytext component to get an array containingall of the actions supported by it.Often it's convenient to load the array of actionsinto a <code>HashMap</code> so your program can retrievean action by name.Here's the code from <code>TextComponentDemo</code>that gets the actions from the text pane and loadsthem into a <code>HashMap</code>:<blockquote><pre>private void createActionTable(JTextComponent textComponent) {    actions = new HashMap();    Action[] actionsArray = textComponent.getActions();    for (int i = 0; i < actionsArray.length; i++) {        Action a = actionsArray[i];        actions.put(a.getValue(Action.NAME), a);    }}    </pre></blockquote>Here's a convenient method for retrieving anaction by its name from the hash map:<blockquote><pre>private Action getActionByName(String name) {    return (Action)(actions.get(name));}</pre></blockquote>You can use both methods verbatim in your programs.<p>Now let's look at how the <strong>Cut</strong> menu item is created andassociated with the action of removing text from the text component:<blockquote><pre>protected JMenu createEditMenu() {    JMenu menu = new JMenu("Edit");    ...    menu.add(getActionByName(DefaultEditorKit.cutAction));    ...</pre></blockquote>This code gets the action by name using the handymethod shown previously.It then adds the action to the menu.That's all you need to do. The menuand the action take care of everything else.You'll note that the name of the actioncomes from<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DefaultEditorKit.html"><code>DefaultEditorKit</code></a>.This kit provides actions for basic text editingand is the superclass for all the editor kits provided by Swing.So its capabilities are available to all text componentsunless overridden by a customization.<p>For efficiency,text components share actions.The <code>Action</code> object returned by<code>getActionByName(DefaultEditorKit.cutAction)</code>is shared by the uneditable <code>JTextArea</code>at the bottom of the window.This has two important ramifications:<ul><li> Generally speaking, you shouldn't modify     <code>Action</code> objects you get from editor kits.     If you do, the changes affect     all text components in your program.<li> <code>Action</code> objects can operate     on other text components in the program,     perhaps more than you intended.     In this example, even though it's uneditable,     the <code>JTextArea</code> shares     actions with the <code>JTextPane</code>.     (Select some text in the text area,     then choose the <code>cut-to-clipboard</code> menu item.     You'll hear a beep because the text area is uneditable.)     If you don't want to share,     consider instantiating the <code>Action</code> object yourself.     <code>DefaultEditorKit</code> defines a number of     useful <code>Action</code> subclasses.</ul>Here's the code that creates the <strong>Style</strong> menu and puts the<strong>Bold</strong> menu item in it:<blockquote><pre>protected JMenu createStyleMenu() {    JMenu menu = new JMenu("Style");     Action action = new StyledEditorKit.BoldAction();    action.putValue(Action.NAME, "Bold");    menu.add(action);    ...</pre></blockquote>The <code>StyledEditorKit</code>provides <code>Action</code> subclasses to implementediting commands for styled text.You'll note thatinstead of getting the action from the editor kit,this code creates aninstance of the <code>BoldAction</code> class.Thus, this action is not shared with any other text component,and changing its name won't affect any other text component.</blockquote><a name="bindingkeystrokes"><h3>Associating Text Actions with Key Strokes</h3></a> <blockquote> In addition to associating an action with a GUI component,you can also associate an action with a key stroke,using a text component's input map.Input maps are described in<a class="TutorialLink" target="_top" href="../misc/keybinding.html">How to Use Key Bindings</a>.<p>The text pane in the <code>TextComponentDemo</code>supports four key bindings not provided by default.<ul><li> <code>CTRL-B</code> for moving the caret backward one character<li> <code>CTRL-F</code> for moving the caret forward one character<li> <code>CTRL-N</code> for moving the caret down one line<li> <code>CTRL-P</code> for moving the caret up one line</ul>The following code adds the <code>CTRL-B</code> key bindingto the text pane.The code for adding the other three is similar.<blockquote><pre>InputMap inputMap = textPane.getInputMap();KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B,                                       Event.CTRL_MASK);inputMap.put(key, DefaultEditorKit.backwardAction);</pre></blockquote><p>The code starts off by getting the text component's input map.Next, it gets a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/KeyStroke.html"><code>KeyStroke</code></a> object representing the<code>CTRL-B</code> key sequence.Finally, the code binds the key stroke to the <code>Action</code> that moves the cursor backward.</blockquote><a name="undo"><h3>Implementing Undo and Redo</h3></a> <blockquote> Implementing undo and redo has two parts:<ul><li> <a href="#undoableedits">Remembering undoable edits</a>.<li> <a href="#undoredoactions">Implementing the undo and redo commands</a>     and providing a user interface for them.</ul><p><a name="undoableedits"><strong>Part 1: Remembering Undoable Edits</strong></a><br>To support undo and redo, a text component must remembereach edit that occurs,the order of edits,and what it takes to undo each edit.The example program uses an instance of the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/undo/UndoManager.html"><code>UndoManager</code></a> classto manage its list of undoable edits.The undo manager is created where the member variables are declared:<blockquote><pre>protected UndoManager undo = new UndoManager();</pre></blockquote>Now, let's look at how the program finds out aboutundoable edits and adds them to the undo manager.<p>A document notifies interested listenerswhenever an undoable edit occurs on its content.An important step in implementingundo and redo is to register an undoable edit listener on thedocument of the text component.The following code adds an instance of <code>MyUndoableEditListener</code>to the text pane's document:<blockquote><pre>lsd.addUndoableEditListener(new MyUndoableEditListener());</pre></blockquote>The undoable edit listener used in our exampleadds the edit to the undo manager's list:<blockquote><pre>protected class MyUndoableEditListener          implements UndoableEditListener{    public void undoableEditHappened(UndoableEditEvent e) {        //Remember the edit and update the menus        undo.addEdit(e.getEdit());        undoAction.updateUndoState();        redoAction.updateRedoState();    }}  </pre></blockquote>Note that this method updates two objects:<code>undoAction</code> and <code>redoAction</code>.These are the action objects attached to the <strong>Undo</strong>and <strong>Redo</strong> menu items, respectively.The next step shows you how the menu items are createdand the implementation of the two actions.For general information about undoable edit listenersand undoable edit events,see<a href="../events/undoableeditlistener.html">How to Write an Undoable Edit Listener</a>.<blockquote><hr><strong>Note:</strong>&nbsp;By default, undoable edits can beas fine-grained as single key presses.It is possible, with some effort,to group edits so that (for example)a series of key presses is combinedinto one undoable edit.The implementation would requiredefining a classthat intercepts undoable edit eventsfrom the document, combining them if appropriateand forwarding the results to your undoable edit listener.<hr></blockquote><p><a name="undoredoactions"><strong>Part 2: Implementing the Undo and Redo Commands</strong></a><br>The first step in this part of implementing undo and redo isto create the actions to put in the <strong>Edit</strong> menu.<blockquote><pre>JMenu menu = new JMenu("Edit");//Undo and redo are actions of our own creationundoAction = new UndoAction();menu.add(undoAction);redoAction = new RedoAction();menu.add(redoAction);...</pre></blockquote>The undo and redo actions are implemented bycustom <code>AbstractAction</code> subclasses:<code>UndoAction</code> and <code>RedoAction</code>, respectively.These classes are inner classes of the example's primary class.<p>When the user invokes the <strong>Undo</strong> command,<code>UndoAction</code>'s <code>actionPerformed</code> method,shown here, gets called:<blockquote><pre>public void actionPerformed(ActionEvent e) {    try {        undo.undo();    } catch (CannotUndoException ex) {        System.out.println("Unable to undo: " + ex);        ex.printStackTrace();    }    updateUndoState();    redoAction.updateRedoState();}</pre></blockquote>This method calls the undo manager's <code>undo</code>method and updates the menu items to reflect the new undo/redo state.<p>Similarly, when the user invokes the <strong>Redo</strong> command,the <code>actionPerformed</code> method in <code>RedoAction</code>gets called:<blockquote><pre>public void actionPerformed(ActionEvent e) {    try {        undo.redo();    } catch (CannotRedoException ex) {        System.out.println("Unable to redo: " + ex);        ex.printStackTrace();    }    updateRedoState();    undoAction.updateUndoState();}</pre></blockquote>This method is similar except that it callsthe undo manager's <code>redo</code> method.<p>Much of the code in the <code>UndoAction</code>and <code>RedoAction</code> classes is dedicated toenabling and disabling the actions as appropriate forthe current state, and changing the names of the menuitems to reflect the edit to be undone or redone.<blockquote><hr><strong>Note:</strong>&nbsp;The implementation of undo and redo in <code>TextComponentDemo</code>was taken from the <code>NotePad</code> demo that comes with the JDK.Many programmers will also be able to copy this implementation ofundo/redo without modification.<hr></blockquote></blockquote><a name="document"><h3>Concepts: About Documents</h3></a><blockquote>Like other Swing components, a text component separates its data (known as the<em>model</em>) from its view of the data.If you are not yet familiar with the model-view splitused by Swing components,refer to<a href="model.html">Using Models</a>.<p>A text component's model is known asa <em>document</em>and is an instance of a class that implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/Document.html"><code>Document</code></a> interface.A document provides these services for a text component:<ul><li> Contains the text. A document stores the textual     content in <code>Element</code> objects,     which can represent any logical text structure,     such as paragraphs, text runs that share styles, and so on.     We do not cover <code>Element</code>s.     However,<a class="OutsideLink" target="_blank" href="http://java.sun.com/products/jfc/tsc/index.html"><em>The Swing Connection</em></a>     has at least     one article on the subject.<li> Provides support for editing the text through     the <code>remove</code> and <code>insertString</code> methods.<li> Notifies document listeners     and undoable edit listeners of changes to the text.<li> Manages <code>Position</code> objects,     which track a particular location within the text     even as the text is modified.<li> Allows you to get information about the text, such as its length,     and segments of the text as a string.</ul>The Swing text package containsa subinterface of <code>Document</code>,<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/StyledDocument.html"><code>StyledDocument</code></a>, that adds support for marking up the text with styles.One <code>JTextComponent</code> subclass,<code>JTextPane</code>,requires that its document be a <code>StyledDocument</code>rather than merely a <code>Document</code>.<p>The <code>javax.swing.text</code> package providesthe following hierarchy of document classes,which implement specialized documents for thevarious <code>JTextComponent</code> subclasses:<p><center><IMG SRC="../../figures/uiswing/components/10model.gif" WIDTH="444" HEIGHT="187" ALIGN="BOTTOM" ALT="The hierarchy of document classes that javax.swing.text provides."></center></p>A <code>PlainDocument</code> is the defaultdocument for text fields, password fields, and text areas.

⌨️ 快捷键说明

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