focuslistener.html

来自「jsf、swing的官方指南」· HTML 代码 · 共 663 行 · 第 1/2 页

HTML
663
字号
            </div>            <div id=PageTitle>How to Write a Focus Listener</div>            <blockquote>Focus events are fired whenever a component gains orloses the keyboard focus.This is true whether the change in focus occursthrough the mouse, the keyboard, or programmatically.If you're unfamiliar with basic focus concepts or wantdetailed information about focus, see<a class="TutorialLink" target="_top" href="../misc/focus.html">How to Use the Focus Subsystem</a>.<p>This section explains how to get focus events for aparticular component by registering a <code>FocusListener</code>on it.  If you're only interested in focus events for windows,you might want to implement a<a href=windowlistener.html><code>WindowFocusListener</code></a>instead. If you need to know the focus status of manycomponents, consider implementing a <code>PropertyChangeListener</code>on the <code>KeyboardFocusManager</code>, as described in<a class="TutorialLink" target="_top" href="../misc/focus.html#trackingFocus">Tracking Focus Changes to Multiple Components</a> in<a class="TutorialLink" target="_top" href="../misc/focus.html">How to Use the Focus Subsystem</a>.<blockquote><hr><strong>Version note:</strong>&nbsp;The focus subsystem was completely rearchitected in release 1.4. This section uses concepts and methods introducedin that release.<hr></blockquote><p>The following example demonstrates focus events.The window displays a variety of components.A focus listener, registered on each component,reports every focus-gained and focus-lost event.For each event, the other component involvedin the focus change, the <em>opposite component</em>,is reported.  For example, when the focusgoes from a button to a text field, a focus-lostevent is fired by the button (with the text field asthe opposite component) and then a focus-gainedevent is fired by the text field (with the button as theopposite component).Focus-lost events can be temporary, which occurswhen the window loses the focus, for example.<p><p><center><IMG SRC="../../figures/uiswing/events/FocusEventDemoWindow.png" WIDTH="458" HEIGHT="324" ALIGN="BOTTOM" ALT="The Focus Event Window, which demonstrates the events that are fired when the keyboard focus changes."></center></p><h4 align=center><font color=red>[PENDING: new screenshot forthcoming with     several samples of output]</font></h4><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/events/examples/FocusEventDemo.jnlp">Run     FocusEventDemo</a> using     <a href=http://java.sun.com/products/javawebstart>     Java<sup><font size=-2>TM</font></sup> Web Start</a>.     Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#FocusEventDemo">example index</a>.<li> You'll see a "Focus gained: JTextField" message     in the text area &#151; its "opposite component" is      null, since it is the first component to have the focus.<li> Click the label.  Nothing happens because the label,     by default, can't get the focus.<li> Click the combo box. A focus-lost event is fired by     the text field and a focus-gained event by the combo box.     The combo box now shows that it has the focus, perhaps with     a dotted line around the text &#151; exactly how this is     represented is look and feel dependent.     <br>     Notice that when the focus changes from one component to another,     the first component fires a focus-lost event     before the second component fires a focus-gained event.<li> Select a choice from the combo box's menu. Click the     combo box again. Notice that no focus event is     reported.  As long as the user manipulates     the same component, the focus stays on that component.<li> Click the text area where the focus events are printed.     Nothing happens because the text area has been rendered     un-clickable with <code>setRequestFocusEnabled(false)</code>.<li> Click the text field to return the focus to the     initial component. <li> Press Tab on the keyboard. The focus moves to the combo box     and skips over the label.<li> Press Tab again. The focus moves to the button.<li> Click another window so that the FocusEventDemo window     loses the focus.  A temporary focus-lost event is     generated for the button.<li> Click the top of the FocusEventDemo window.     A focus-gained event is fired by the button.<li> Press Tab on the keyboard. The focus moves to the list.<li> Press Tab again.  The focus moves to the text area.     <br>     Notice that even though you can't click on the text area,     you can tab to it.  This is so users who use <a class="TutorialLink" target="_top" href="../misc/access.html">assistive technologies</a> can determine that a component is there and what it contains.     The demo disables click to focus for the text area,     while retaining its tab-to-focus capability,     by invoking <code>setRequestFocusEnabled(false)</code>     on the text area.  The demo could use      <code>setFocusable(false)</code> to truly remove the     text area from the focus cycle, but that would have     the unfortunate effect of making the component     unavailable to those who use assistive technologies.<li> Press Tab again. The focus moves from the list back to     the text field.  You have just completed a <em>focus     cycle</em>. See the<a class="TutorialLink" target="_top" href="../misc/focus.html#intro">introduction</a> in<a class="TutorialLink" target="_top" href="../misc/focus.html">How to Use the Focus Subsystem</a> for a discussion of focus terminology and concepts.</ol><hr></blockquote><p>You can find the demo's code in <a class="SourceLink" target="_blank" href="examples/FocusEventDemo.java"><code>FocusEventDemo.java</code></a>.Here is the code that's related to focus-event handling:<blockquote><pre>public class FocusEventDemo ... implements FocusListener ... {    public FocusEventDemo() {        ...        JTextField textField = new JTextField("A TextField");        textField.addFocusListener(this);        ...	JLabel label = new JLabel("A Label");	label.addFocusListener(this);        ...        JComboBox comboBox = new JComboBox(vector);        comboBox.addFocusListener(this);        ...        JButton button = new JButton("A Button");        button.addFocusListener(this);        ...        JList list = new JList(listVector);        list.setSelectedIndex(1); //It's easier to see the focus change                                  //if an item is selected.        list.addFocusListener(this);        JScrollPane listScrollPane = new JScrollPane(list);        //We want to prevent the list's scroll bars        //from getting the focus - even with the keyboard.        //Note that in general we prefer setRequestFocusable        //over setFocusable for reasons of accessibility,        //but this is to work around bug #4866958.        listScrollPane.getVerticalScrollBar().setFocusable(false);        listScrollPane.getHorizontalScrollBar().setFocusable(false);        ...        //Set up the area that reports focus-gained and focus-lost events.        display = new JTextArea();        display.setEditable(false);        //The method setRequestFocusEnabled prevents a        //component from being clickable, but it can still        //get the focus through the keyboard - this ensures        //user accessibility.        display.setRequestFocusEnabled(false);        display.addFocusListener(this);        JScrollPane displayScrollPane = new JScrollPane(display);        //Work around for bug #4866958.        displayScrollPane.getHorizontalScrollBar().setFocusable(false);        displayScrollPane.getVerticalScrollBar().setFocusable(false);        ...    }    ...    public void focusGained(FocusEvent e) {	displayMessage("Focus gained", e);    }    public void focusLost(FocusEvent e) {	displayMessage("Focus lost", e);    }    void displayMessage(String prefix, FocusEvent e) {	display.append(prefix                       + (e.isTemporary() ? " (temporary):" : ":")                       +  e.getComponent().getClass().getName()                       + "; Opposite component: "                        + (e.getOppositeComponent != null ?                          e.getOppositeComponent().getClass().getName() : "null")		       + newline);     }    ...}</pre></blockquote></blockquote><h3><a name="api">The Focus Listener API</a></h3><blockquote><p align=center><a name="focuslistener">The FocusListener   Interface</a><p><em>The corresponding adapter class is<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/FocusAdapter.html"><code>FocusAdapter</code></a>.</em><table border=1><tr><th align=left>Method</th><th align=left>Purpose</th></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/FocusListener.html#focusGained(java.awt.event.FocusEvent)">focusGained(FocusEvent)</a></td><td> Called just after the listened-to component gets the focus.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/FocusListener.html#focusLost(java.awt.event.FocusEvent)">focusLost(FocusEvent)</a></td><td> Called just after the listened-to component loses the focus.</td></tr></table><p align=center><a name="focusevent">The FocusEvent API</a><p><table border=1><tr><th align=left>Method</th><th align=left>Purpose</th></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/FocusEvent.html#isTemporary()">boolean isTemporary()</a></td><td> Returns true if a focus-lost event is temporary.     This occurs, for example, when the component's window loses the focus.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/ComponentEvent.html#getComponent()">Component getComponent()</a><br>(<em>in <code>java.awt.event.ComponentEvent</code></em>)</td><td> Returns the component that fired the focus event.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/FocusEvent.html#getOppositeComponent()">Component getOppositeComponent()</a></td><td> Returns the other component involved in the focus change.     For a <code>FOCUS_GAINED</code> event, this is the      component that lost the focus.  For a <code>FOCUS_LOST</code>     event, this is the component that gained the focus. If the     focus change involves a native application, a     Java application in a different VM or context, or     no other component, then <code>null</code> is returned.      This method was introduced in release 1.4.</td></tr></table></blockquote><a name="eg"><h3>Examples that Use Focus Listeners</h3></a><blockquote>The following table lists theexamples that use focus listeners.<p><table><tr><th align=left> Example</th><th align=left> Where Described</th><th align=left> Notes </th></tr><tr valign=top><td> <a href="examples/index.html#FocusEventDemo"><code>FocusEventDemo</code></a></td><td> This section</td><td> Reports all focus events that occur on several components     to demonstrate the circumstances under which focus events are fired.</td></tr><tr valign=top><td><a class="TutorialLink" target="_top" href="../misc/examples/index.html#TrackFocusDemo"><code>TrackFocusDemo</code></a></td><td> <a class="TutorialLink" target="_top" href="../misc/focus.html">How to Use the Focus Subsystem</a></td><td> The custom component,<a class="TutorialLink" target="_top" href="../misc/examples/Picture.java"><code>Picture</code></a>, implementsa focus listener to draw a red border around thecomponent when it is the current focus owner.</td></tr></table>        </blockquote>        <div class=NavBit>            <a target=_top href=documentlistener.html>&laquo; Previous</a>            &bull;            <a target=_top href=../TOC.html>Trail</a>            &bull;            <a target=_top href=internalframelistener.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> How to Write a Document Listener        <br><b>Next page:</b> How to Write an Internal Frame Listener    </div>    </body></html> 

⌨️ 快捷键说明

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