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

📄 focus.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 4 页
字号:
it must satisfy three requirements:  it must be visible, enabled,and focusable. It is also likely that you'll want togive it an input map. If you don't know what an input map is, please read<a class="TutorialLink" target="_top" href="../misc/keybinding.html">How to Use Key Bindings</a>.<p>The <a href="#trackfocusdemo">TrackFocusDemo</a>example defines the simple component <code>Picture</code>.Here is its constructor:<blockquote><pre>public Picture(Image image) {    this.image = image;    setFocusable(true);    addMouseListener(this);    addFocusListener(this);}</pre></blockquote><p>The call to <code>setFocusable(true)</code> makes thecomponent focusable.  If you explicitly give your componentkey bindings in its <code>WHEN_FOCUSED</code> input map,you don't need to call <code>setFocusable</code>.<p> To visually show changes in the focus(by drawing a red border only when the component hasthe focus), <code>Picture</code> has a<a class="TutorialLink" target="_top" href="../events/focuslistener.html">focus listener</a>.<p>To gain the focus when the user clicks on the picture,the component has a <a class="TutorialLink" target="_top" href="../events/mouselistener.html">mouse listener</a>. The listener's <code>mouseClicked</code> method requestsfor the focus to be transferred to the picture. Here is the code:<blockquote><pre>public void mouseClicked(MouseEvent e) {    //Since the user clicked on us, let's get focus!    requestFocusInWindow();}</pre></blockquote><p>See <a href=#trackingFocus>Tracking Focus Changes to MultipleComponents</a> for more discussion of the TrackFocusDemo example.</blockquote><a name=customFocusTraversal><h2>Customizing Focus Traversal</h2></a><blockquote><p>The focus subsystem determines a default order that isused when using the focus traversal keys (such as Tab) to navigate.A Swing application has its policy determined by<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/LayoutFocusTraversalPolicy.html"><code>LayoutFocusTraversalPolicy</code></a> . You can set a focus traversal policy on any<code>Container</code>, though if the container isnot a focus cycle root, it may have no apparent effect.<p>The <code>FocusTraversalDemo</code> example demonstrates how to customize focus behavior.<font color=red><p align=center>[PENDING: Screenshot forthcoming]</font><a name=focustraversaldemo><p></a><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/FocusTraversalDemo.jnlp">Run     FocusTraversalDemo</a> using     <a href=http://java.sun.com/products/javawebstart>Java Web Start</a>.     Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#FocusTraversalDemo">example index</a>.<li> Click the window, if necessary, to give it the focus.<li> Note the focus order as you tab through     the components.  The focus order was determined by     the order that the components were added to the content pane.     Note also that the check box never gets the focus; we     removed it from the focus cycle.<li> To move the focus out of the table, use Control-Tab or     Control-Shift-Tab.<li> Click the <b>Custom FocusTraversalPolicy</b> check box.     This installs a custom focus traversal policy on the frame.<li> Try tabbing through the components again.  Note that     the focus order is now in numeric (left-to-right, top-down)     order.</ol><hr></blockquote><p>You can find the demo's code in <a class="SourceLink" target="_blank" href="examples/FocusTraversalDemo.java"><code>FocusTraversalDemo.java</code></a>.<p>The check box was removed from the focus cyclewith this line of code:<blockquote><pre>togglePolicy.setFocusable(false);</pre></blockquote>Here is the application's custom <code>FocusTraversalPolicy</code>:<blockquote><pre>    ...    JTextField tf1, tf2, tf3, tf4, tf5, tf6;    JTable table;    ...    public class MyOwnFocusTraversalPolicy                 extends FocusTraversalPolicy {        public Component getComponentAfter(Container focusCycleRoot,                                           Component aComponent) {            if (aComponent.equals(tf1)) {                return tf2;            } else if (aComponent.equals(tf2)) {                return tf3;            } else if (aComponent.equals(tf3)) {                return tf4;            } else if (aComponent.equals(tf4)) {                return tf5;            } else if (aComponent.equals(tf5)) {                return tf6;            } else if (aComponent.equals(tf6)) {                return table;            } else if (aComponent.equals(table)) {                return tf1;            }            return tf1;        }        public Component getComponentBefore(Container focusCycleRoot,                                       Component aComponent) {            if (aComponent.equals(tf1)) {                return table;            } else if (aComponent.equals(tf2)) {                return tf1;            } else if (aComponent.equals(tf3)) {                return tf2;            } else if (aComponent.equals(tf4)) {                return tf3;            } else if (aComponent.equals(tf5)) {                return tf4;            } else if (aComponent.equals(tf6)) {                return tf5;            } else if (aComponent.equals(table)) {                return tf6;            }            return tf1;        }        public Component getDefaultComponent(Container focusCycleRoot) {            return tf1;        }        public Component getLastComponent(Container focusCycleRoot) {            return table;        }        public Component getFirstComponent(Container focusCycleRoot) {            return tf1;        }    }</pre></blockquote><p>To use a custom <code>FocusTraversalPolicy</code>,use code like the following on any focus cycle root.<blockquote><pre>    MyOwnFocusTraversalPolicy newPolicy = new MyOwnFocusTraversalPolicy();    frame.setFocusTraversalPolicy(newPolicy);</pre></blockquote><p>You can remove the custom focus traversal policy by setting the <code>FocusTraversalPolicy</code> to <code>null</code>. This restores the default policy.</blockquote><a name=trackingFocus><h2>Tracking Focus Changes to Multiple Components</h2></a><blockquote><p>In some situations an application may need to track which component hasthe focus. This information might be used to dynamically update menusor perhaps a status bar. If you need to trackthe focus only on specific components, it may make sense to implement a<a class="TutorialLink" target="_top" href="../events/focuslistener.html">focus event listener</a> .<p>If a focus listener isn't appropriate, you can insteadregister a <code>PropertyChangeListener</code> on the<code>KeyboardFocusManager</code>. The property changelistener is notified of every changeinvolving the focus, including changes to thefocus owner, the focused window, and the default focus traversal policy.  See the<a href=#properties>KeyboardFocusManagerProperties</a> table for a complete list.<p><a name="trackfocusdemo">The</a>following example demonstrates tracking the focus ownerby installing a property change listener on the keyboard focus manager.<p><center><IMG SRC="../../figures/uiswing/misc/TrackFocusDemo.png" WIDTH="458" HEIGHT="384" ALIGN="BOTTOM" ALT="The TrackFocusDemo example, which demonstrates tracking the focus owner."></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/TrackFocusDemo.jnlp">Run     TrackFocusDemo</a> using     <a href=http://java.sun.com/products/javawebstart>Java Web Start</a>.     Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#TrackFocusDemo">example index</a>.<li> Click the window, if necessary, to give it the focus.<li> The window shows six images, each are displayed by     a <code>Picture</code> component. The <code>Picture</code>     that has the focus is indicated with a red     border. A label at the bottom of the window     describes the <code>Picture</code> that has the focus.<li> Move the focus to another <code>Picture</code> by tabbing,     Shift-tabbing, or clicking an image.     Because a property change listener has been     registered on the keyboard focus manager,     the change in focus is detected and the label is     updated appropriately.</ol><hr></blockquote><p>You can view the demo's code in <a class="SourceLink" target="_blank" href="examples/TrackFocusDemo.java"><code>TrackFocusDemo.java</code></a>. The custom component used for drawing the images is in<a class="SourceLink" target="_blank" href="examples/Picture.java"><code>Picture.java</code></a>.  Here is the code that defines and installs theproperty change listener:<blockquote><pre>KeyboardFocusManager focusManager =    KeyboardFocusManager.getCurrentKeyboardFocusManager();focusManager.addPropertyChangeListener(    new PropertyChangeListener() {        public void propertyChange(PropertyChangeEvent e) {            String prop = e.getPropertyName();            if (("focusOwner".equals(prop)) &&                  (e.getNewValue() != null) &&                  ((e.getNewValue()) instanceof Picture)) {                Component comp = (Component)e.getNewValue();                String name = comp.getName();                Integer num = new Integer(name);                int index = num.intValue();                if (index < 0 || index > comments.length) {                    index = 0;                }                info.setText(comments[index]);            }        }    });</pre></blockquote><p>The custom component, <code>Picture</code>,is responsible for drawing the image.  All sixcomponents are defined in this manner:<blockquote><pre>pic1 = new Picture(createImageIcon("images/" +            mayaString + ".gif", mayaString).getImage());pic1.setName("1");</pre></blockquote></blockquote><a name=transferTiming><h2>Timing Focus Transfers</h2></a><blockquote><p>Focus transfers are asynchronous. This can lead to some oddtiming-related problems and assumptions, especially during automatictransfers of the focus.  For example, imagine anapplication with a window containing a Start button,a Cancel button and a text field. The components are added in this order:<ol><li>Start button<li>Text field<li>Cancel button</ol>When an application is launched, the<code>LayoutFocusTraversalPolicy</code>determines the focus traversal policy &#151;in this case, it's the order that the componentswere added to their container.In this example, the desired behavior is that the Start button has the initial focus, and when theStart button is clicked it is disabled and the Cancelbutton gets the focus.The correct way toimplement this would be to add the componentsto the container in the desired order or tocreate a custom focus traversal policy.If, for some reason, that was not possible,the way to implement this would bewith the following code snippet:<blockquote><pre>public void actionPerformed(ActionEvent e) {    //This works.    start.setEnabled(false);    cancel.requestFocusInWindow();}</pre></blockquote><p>As desired, the focus goes from the Start button to theCancel button, rather than to the text field.But a different result would occur if the same methods werecalled in the opposite order, like this:<blockquote><pre>public void actionPerformed(ActionEvent e) {    //This doesn't work.    cancel.requestFocusInWindow();    start.setEnabled(false);}</pre></blockquote>In this case, the focus is requested on the Cancel button beforeit has left the Start button.The call to <code>requestFocusInWindow</code>initiates the focus transfer, but it doesn't immediately move the focusto the Cancel button.When the Start button is disabled, the focus istransferred to the next component (so there is always a componentwith the focus) and, in this case, it would then move the focus to thetext field, <em>not</em> the Cancel button.<p>The need to make focus requests after all other changes thatmight affect the focus applies to:<ul><li>Hiding the focus owner.<li>Making the focus owner non-focusable.<li>Calling <code>removeNotify</code> on the focus owner.<li>Doing any of the above to the container of the focus owner,    or causing changes to the focus policy so the container no    longer accepts the component as the focus owner.<li>Disposing of the top-level window that contains the focus owner.</ul></blockquote><h3><a name="api">The Focus API</a></h3><blockquote>The following tables list the commonly usedconstructors and methods related to focus.The focus API falls into four categories:<ul><li><a href="#focusMethods">Useful Methods for Components</a><li><a href="#focustraversal">Creating and Using a Custom     FocusTraversalPolicy</a><li><a href="#inputverificationapi">Input Verification API</a><li><a href="#properties">KeyboardFocusManager Properties</a></ul><p>For more detailed information about the focus architecture,see the specification for the<a class="OutsideLink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/doc-files/FocusSpec.html">Focus Subsystem</a>. You may also find<a class="TutorialLink" target="_top" href="../events/focuslistener.html">How to Write a Focus Listener</a> useful.<p align=center><a name="focusMethods">Useful Methods for Components</a><p><em>All of this API was introduced in release 1.4.</em><table border=1><tr><th align=left>Method (in <code>Component</code>)</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/Component.html#isFocusOwner()">isFocusOwner()</a></td><td>Return <code>true</code> if the component is the focus    owner. This method, introduced in release 1.4,    obsoletes <code>hasFocus</code>.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#setRequestFocusEnabled(boolean)">setRequestFocusEnabled(boolean)</a><br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#isRequestFocusEnabled()">isRequestFocusEnabled()</a><br>(<em>in <code>JComponent</code>)</em></td><td>Set or get the hint on whether this <code>JComponent</code> shouldget the focus. Setting <code>setRequestFocusEnabled(false)</code>typically prevents mouse clicks from giving the component the focus,while still allowing keyboard navigation to give the component the focus.This method applies only to components thatreceive mouse events. For example, you can use this methodon a <code>JButton</code>, but not on a <code>JPanel</code>.If you write a custom component it is up to you to honor this property.We recommend this method over <code>setFocusable</code> so thatyour program works better for users employing <a href=access.html>assistive technologies</a>.</td></tr><tr>

⌨️ 快捷键说明

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