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

📄 focus.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 4 页
字号:
<li><a href=#focusable>Making a Custom Component Focusable</a><li><a href=#customFocusTraversal>Customizing Focus Traversal</a><li><a href=#trackingFocus>Tracking Focus Changes to Multiple Components</a><li><a href=#transferTiming>Timing Focus Transfers</a><li><a href=#api>The Focus API</a><li><a href=#eg>Focus Examples</a></ul></blockquote><a name=intro><h2>Introduction to the Focus Subsystem</h2></a><blockquote><p>The focus subsystem is designed to do the rightthing as invisibly as possible.  In most cases itbehaves in a reasonable manner, and if it doesn'tyou can tweak its behavior in various ways.Some common scenarios might include:<ul><li> The ordering is right but the first component     with the focus isn't. As shown in the preceding code     snippet, you can use <code>requestFocusInWindow</code>     to set the focused component when the window becomes     visible.<li> The ordering is wrong. To fix this,     you can change the containment hierarchy,     you can change the order that the components     are added to their containers, or you can create a custom     focus traversal policy.  For more details see     <a href=#customFocusTraversal>Customizing Focus Traversal</a>.<li> A component needs to be prevented from losing focus,     or you need to check a value in a component before it     loses focus.     <a href=#inputVerification>Input verification</a>     is a solution to this problem.<li> A custom component isn't getting the focus.     To fix this, you need to make sure that it     satisfies all the requirements outlined in     <a href=#focusable>Making a Custom Component Focusable</a>.</ul><p>The <code>FocusConceptsDemo</code> example illustrates a few concepts.<p><center><IMG SRC="../../figures/uiswing/misc/FocusConceptsDemo.png" WIDTH="488" HEIGHT="360" ALIGN="BOTTOM" ALT="The FocusConceptsDemo example"></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/FocusConceptsDemo.jnlp">Run     FocusConceptsDemo</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#FocusConceptsDemo">example index</a>.<li> Click the window, if necessary, to give it the focus.<li> Move the focus from component to component using the Tab key.<br> You'll notice that when the focus moves into the text area,     it stays in the text area.<li> Move the focus out of the text area using Control-Tab.<li> Move the focus in the opposite direction using Shift-Tab.<li> Move the focus out of the text area in the opposite direction using     Control-Shift-Tab.</ol><hr></blockquote><p>At the heart of the focus subsystem is the<code>KeyboardFocusManager</code>,which manages state and initiates changes.The keyboard manager tracks the <i>focus owner</i> &#151;the component that receives typing from the keyboard.  The <i>focused window</i> is the window that containsthe focus owner.<blockquote><hr><strong>JWindow and focus:</strong>&nbsp;If you happen to use a <code>JWindow</code> in your GUI,you should know that the <code>JWindow</code>'s owning frame mustbe visible for any components in the window to get the focus.By default, if you don't specify an owning frame fora <code>JWindow</code>, an invisible owning frame iscreated for it.  The result is that components in<code>JWindow</code>s might not be able to get the focus.The solution is to either specify avisible owning frame when creating the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JWindow.html"><code>JWindow</code></a>, or to use an undecorated<a class="TutorialLink" target="_top" href="../components/frame.html"><code>JFrame</code></a> instead of <code>JWindow</code>.<hr></blockquote><p>A <i>focus cycle</i> (or <i>focus traversal cycle</i>)is a set of components, typicallythe components that share a common ancestor in thecontainment hierarchy.The <i>focus cycle root</i> is thecontainer that is the root for a particularfocus traversal cycle.  By default, every<code>Window</code> and <code>JInternalFrame</code>is a focus cycle root.  Any <code>Container</code>(and remember that all Swing components are containers)can be a focus cycle root; a focus cycle root can itself contain one or more focus cycle roots.The following Swing objects are focus cycle roots:<code>JApplet</code>, <code>JDesktopPane</code>, <code>JDialog</code>,<code>JEditorPane</code>, <code>JFrame</code>, <code>JInternalFrame</code>,and <code>JWindow</code>.While it might appear that <code>JTable</code>and <code>JTree</code> are focus cycle roots, theyare not.<p>A <i>focus traversal policy</i> determines the order in whicha group of components are navigated. Swing providesthe<a class="SourceLink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/LayoutFocusTraversalPolicy.html"><code><code>LayoutFocusTraversalPolicy</code></code></a> class, whichdecides the order of navigation based on layoutmanager-dependent factors, such as size,location, and orientation of components.  Within a focuscycle, components can be navigated in a forwards orbackwards direction.  In a hierarchy of focus cycleroots, upwards traversal takes the focus out of the current cycle into the parent cycle.<a name=addreturn><p></a>In most look and feels,components are navigated using theTab and Shift-Tab keys.  These are the default<i>focus traversal keys</i> and can be changedprogrammatically.  For example, you can add Enteras a forward focus traversal key with the followingfour lines of code:<blockquote><pre>Set forwardKeys = getFocusTraversalKeys(    KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);Set newForwardKeys = new HashSet(forwardKeys);newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,    newForwardKeys);</pre></blockquote> Tab shifts the focus inthe forwards direction.  Shift-Tab moves thefocus in the backwards direction.  For example, in FocusConceptsDemo the firstbutton has the initial focus.  Tabbing movesthe focus through the buttons into the text area.Additional tabbing moves the cursor within the text area but not out of the text area because, inside a text area, Tab is <em>not</em>a focus traversal key.However, Control-Tab moves the focus out of thetext area and into the first text field.Likewise, Control-Shift-Tab movesthe focus out of the text area and into the previouscomponent.  The Control key is used by conventionto move the focus out any component that treats Tabspecially, such as <code>JTable</code>.<p>We've just given you a brief introduction to the focus architecture.If you want more details, 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>. </blockquote><a name=inputVerification><h2>Validating Input</h2></a><blockquote><p>A common requirement of GUI design is a componentthat restricts the user's input &#151; for example, a text fieldthat allows only numeric input in decimal format (money,for example) or a text field that allows only 5 digitsfor a zip code.Release 1.4 provides a handy, easy-to-use<a class="TutorialLink" target="_top" href="../components/formattedtextfield.html">formatted text field</a> component that allows input to be restricted to a variety oflocalizable formats. You can also specify a<a class="TutorialLink" target="_top" href="../components/formattedtextfield.html">a custom formatter</a> for the text field, which can perform special checkingsuch as determining whether values are not just formattedcorrectly, but also reasonable.<p>When you have a component that isn't a text field,or as an alternative to a custom formatter, you can use aninput verifier.  An input verifier allows you toreject specific values, such as a properly formatted butinvalid zip code, or values outside of a desired range,for example a body temperature higher than 110&deg;F.To use an input verifier, you create a subclass of<a class="SourceLink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/InputVerifier.html"><code><code>InputVerifier</code></code></a> (a class introduced in release 1.3), create an instance ofyour subclass, and set the instance as the input verifierfor one or more components. <p>A component's input verifier is consulted whenever thecomponent is about to lose the focus. If the component'svalue is not acceptable, the input verifier can takeappropriate action, such as refusing to yield the focuson the component or replacing the user's input with thelast valid value and then allowing the focus to transferto the next component.<p>The following two examples showmortgage calculators. One uses input verification withstandard text fields and the other uses formattedtext fields.<font color=red><p>[PENDING: When it is available, this willuse the mortgage calculator implemented with a custom formatter.]</font><p><center><IMG SRC="../../figures/uiswing/misc/InputVerificationDemo.png" WIDTH="356" HEIGHT="154" ALIGN="BOTTOM" ALT="The InputVerificationDemo example, which demonstrates"></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/InputVerificationDemo.jnlp">Run     InputVerificationDemo</a> using     <a href=http://java.sun.com/products/javawebstart>Java Web Start</a>.     If you want to compile and run the example yourself,     consult the     <a href="examples/index.html#InputVerificationDemo">example index</a>.<li>Next, <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/FormattedTextFieldDemo.jnlp">run    FormattedTextFieldDemo</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="../components/examples/index.html#ScrollDemo">example    index for components</a>.<li>Compare the two mortgage calculators side by side.     You'll see that the input verification demo    specifies valid input values    in the associated label for each editable text field.     Try entering badly formatted values in both    examples to observe behavior.  Then try entering a properly    formatted, but unreasonable value.</ol><hr></blockquote><p>You can find the code in<a class="SourceLink" target="_blank" href="examples/InputVerificationDemo.java"><code>InputVerificationDemo.java</code></a>. Here is the code for the <code>InputVerifier</code>subclass, <code>MyVerifier</code>:<blockquote><pre>class MyVerifier extends InputVerifier                 implements ActionListener {    double MIN_AMOUNT = 10000.0;    double MAX_AMOUNT = 10000000.0;    double MIN_RATE = 0.0;    int MIN_PERIOD = 1;    int MAX_PERIOD = 40;   public boolean shouldYieldFocus(JComponent input) {        boolean inputOK = verify(input);        makeItPretty(input);        updatePayment();        if (inputOK) {            return true;        } else {            Toolkit.getDefaultToolkit().beep();            return false;        }    }    protected void updatePayment() {        double amount = DEFAULT_AMOUNT;        double rate = DEFAULT_RATE;        int numPeriods = DEFAULT_PERIOD;        double payment = 0.0;        //Parse the values.        try {            amount = moneyFormat.parse(amountField.getText()).                              doubleValue();        } catch (ParseException pe) {}        try {            rate = percentFormat.parse(rateField.getText()).                                 doubleValue();        } catch (ParseException pe) {}        try {            numPeriods = decimalFormat.parse(numPeriodsField.getText()).                              intValue();        } catch (ParseException pe) {}        //Calculate the result and update the GUI.        payment = computePayment(amount, rate, numPeriods);        paymentField.setText(paymentFormat.format(payment));    }    //This method checks input, but should cause no side effects.    public boolean verify(JComponent input) {        return checkField(input, false);    }    protected void makeItPretty(JComponent input) {        checkField(input, true);    }    protected boolean checkField(JComponent input, boolean changeIt) {        if (input == amountField) {            return checkAmountField(changeIt);        } else if (input == rateField) {            return checkRateField(changeIt);        } else if (input == numPeriodsField) {            return checkNumPeriodsField(changeIt);        } else {            return true; //shouldn't happen        }    }    //Checks that the amount field is valid.  If it is valid,    //it returns true; otherwise, returns false.  If the    //change argument is true, this method reigns in the    //value if necessary and (even if not) sets it to the    //parsed number so that it looks good -- no letters,    //for example.    protected boolean checkAmountField(boolean change) {        boolean wasValid = true;        double amount = DEFAULT_AMOUNT;        //Parse the value.        try {            amount = moneyFormat.parse(amountField.getText()).                              doubleValue();        } catch (ParseException pe) {            wasValid = false;        }        //Value was invalid.        if ((amount < MIN_AMOUNT) || (amount > MAX_AMOUNT)) {            wasValid = false;            if (change) {                if (amount < MIN_AMOUNT) {                    amount = MIN_AMOUNT;                } else { // amount is greater than MAX_AMOUNT                    amount = MAX_AMOUNT;                }            }        }        //Whether value was valid or not, format it nicely.        if (change) {            amountField.setText(moneyFormat.format(amount));            amountField.selectAll();        }        return wasValid;    }    //Checks that the rate field is valid.  If it is valid,    //it returns true; otherwise, returns false.  If the    //change argument is true, this method reigns in the    //value if necessary and (even if not) sets it to the    //parsed number so that it looks good -- no letters,    //for example.    protected boolean checkRateField(boolean change) {        <em>...//Similar to checkAmountField...</em>    }    //Checks that the numPeriods field is valid.  If it is valid,    //it returns true; otherwise, returns false.  If the    //change argument is true, this method reigns in the    //value if necessary and (even if not) sets it to the    //parsed number so that it looks good -- no letters,    //for example.    protected boolean checkNumPeriodsField(boolean change) {        <em>...//Similar to checkAmountField...</em>    }    public void actionPerformed(ActionEvent e) {        JTextField source = (JTextField)e.getSource();        shouldYieldFocus(source); //ignore return value        source.selectAll();    }}</pre></blockquote><p>Note that the <code>verify</code> method is implemented todetect invalid values but does nothing else.The <code>verify</code> method exists only to determinewhether the input is valid &#151; it should never bringup a dialog or cause any other side effects.The <code>shouldYieldFocus</code> method calls <code>verify</code>and, if the values are invalid, reigns them in.  The<code>shouldYieldFocus</code> method is allowed to cause sideeffects, in this case, it always formats the text field andmay also change its value.  In our example,<code>shouldYieldFocus</code>always returns true so that the transferof the focus is never actually prevented.  This is just one wayverification can be implemented.  We have also provided a versionof this demo called<a href="examples/index.html#InputVerificationDialogDemo"><code>InputVerificationDialogDemo</code></a>that puts up a dialog when user input is invalid and requiresthe user to enter a legal value.<p>The input verifier is installed using the <code>JComponent</code> <code>setInputVerifier</code> method.For example, <code>InputVerificationDemo</code> has this code:<blockquote><pre>private MyVerifier verifier = new MyVerifier();...amountField.setInputVerifier(verifier);</pre></blockquote></blockquote><a name=focusable><h2>Making a Custom Component Focusable</h2></a><blockquote><p>For a component to gain the focus,

⌨️ 快捷键说明

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