Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Question 1: What listener would you implement to be notified when a particular component has appeared on screen? What method tells you this information?
Answer 1: You would register aComponentListener
on the component. ThecomponentShown
method. This method is called when the window is first displayed or is deiconified.Question 2: What listener would you implement to be notified when the user has finished editing a text field by pressing Enter? What listener would you implement to be notified as each character is typed into a text field? Note that you should not implement a general-purpose key listener, but a listener specific to text.
Answer 2: To be notified when the user presses Enter, you would register anActionListener
on the text field; theactionPerformed
method is called when the user types Enter. Note that the Enter character is not part of the resulting string. To be notified as each character is typed, you would register aDocumentListener
on the text field'sDocument
. TheinsertUpdate
method is then called as each character is typed. Note that this is not the correct way to implement input validation. For that behavior you should check out the Input Verification API section in How to Use the Focus Subsystem.Question 3: What listener would you implement to be notified when a spinners value has changed? How would you get the spinners new value?
Answer 3: To be notified when the value has changed, you would register aChangeListener
on the spinner. You would get the new value through the event's source in thestateChanged
method. The following code snippet shows how this could be done:public void stateChanged(ChangeEvent e) { JSpinner mySpinner = (JSpinner)(e.getSource()); SpinnerNumberModel model = (SpinnerNumberModel)(mySpinner.getModel()); Number currentValue = model.getNumber(); ... }Question 4: The default behavior for the focus subsystem is to consume the focus traversal keys, such as Tab and Shift Tab. Say you want to prevent this behavior in one of your applications components. How would you accomplish this?
Answer 4: You callsetFocusTraversalKeysEnabled(false)
on that particular component. Note that you must then handle focus traversal manually. See How to Write a Key Listener and How to Use the Focus Subsystem for more information.
Exercise 1. Take the
Beeper.java
example and add a text field. Implement it so that when the user has finishing entering data, the system beeps.
Answer 1: SeeBeeper1.java
Exercise 2. Take the
Beeper.java
example and add a selectable component that allows the user to enter a number from 1 to 10. For example, you can use a combo box, a set of radio buttons, or a spinner. Implement it so that when the user has selected the number, the system beeps that many times.
Answer 2: SeeBeeper2.java
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.