How to Write a Focus Listener

 < Day Day Up > 

Focus events are fired whenever a component gains or loses the keyboard focus. This is true whether the change in focus occurs through the mouse, the keyboard, or programmatically. If you're unfamiliar with basic focus concepts or want detailed information about focus, see How to Use the Focus Subsystem (page 583) in Chapter 9.

This section explains how to get focus events for a particular component by registering a FocusListener [9] on it. If you're only interested in focus events for windows , you might want to implement a WindowFocusListener instead. If you need to know the focus status of many components , consider implementing a PropertyChangeListener on the KeyboardFocusManager , as described in Tracking Focus Changes to Multiple Components (page 595) in Chapter 9.

[9] FocusListener API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/FocusListener.html.

Figure 5 demonstrates focus events.

Figure 5. The FocusEventDemo application.

graphics/10fig05.jpg

Version Note: The focus subsystem was completely rearchitected in release 1.4. This section uses concepts and methods introduced in that release.


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 involved in the focus change, the opposite component , is reported . For example, when the focus goes from a button to a text field, a focus-lost event is fired by the button (with the text field as the opposite component) and then a focus-gained event is fired by the text field (with the button as the opposite component). Focus-lost events can be temporary, which occurs when the window loses the focus, for example.

Try This:

  1. graphics/cd_icon.gif

    Run FocusEventDemo using Java Web Start or compile and run the example yourself. [10]

    [10] To run FocusEventDemo using Java Web Start, click the FocusEventDemo link on the RunExamples/events.html page on the CD. You can find the source files here: JavaTutorial/uiswing/events/ example-1dot4/index.html#FocusEventDemo .

  2. You'll see a " Focus gained: JTextField " message in the text areaits opposite component is null, since it is the first component to have the focus.

  3. Click the label. Nothing happens because the label, by default, can't get the focus.

  4. 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 textexactly how this is represented is look and feel dependent. 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.

  5. 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.

  6. Click the text area where the focus events are printed. Nothing happens because the text area has been rendered unclickable with setRequestFocusEnabled(false) .

  7. Click the text field to return the focus to the initial component.

  8. Press Tab on the keyboard. The focus moves to the combo box and skips over the label.

  9. Press Tab again. The focus moves to the button.

  10. Click another window so that the FocusEventDemo window loses the focus. A temporary focus-lost event is generated for the button.

  11. Click the top of the FocusEventDemo window. A focus-gained event is fired by the button.

  12. Press Tab on the keyboard. The focus moves to the list.

  13. Press Tab again. The focus moves to the text area. Notice that even though you can't click on the text area, you can tab to it. This is so users who use assistive technologies 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 setRequestFocusEnabled(false) on the text area. The demo could use setFocusable(false) 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.

  14. Press Tab again. The focus moves from the list back to the text field. You have just completed a focus cycle . See the introduction in How to Use the Focus Subsystem (page 583) in Chapter 9 for a discussion of focus terminology and concepts.

You can find the demo's code in FocusEventDemo.java . Here's the code that's related to focus-event handling:

 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);     }     ... } 

The Focus Listener API

Table 13 lists the methods in the FocusListener interface and Table 14 describes the methods in the FocusEvent class. Also refer to the FocusListener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/FocusListener.html. The FocusEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/FocusEvent.html.

Table 13. The FocusListener Interface (The corresponding adapter class is FocusAdapter . [a] )

Method

Purpose

focusGained(FocusEvent)

Called just after the listened-to component gets the focus.

focusLost(FocusEvent)

Called just after the listened-to component loses the focus.

[a] FocusAdapter API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/FocusAdapter.html.

Table 14. The FocusEvent Class

Method

Purpose

boolean isTemporary()

Return true if a focus-lost event is temporary. This occurs, for example, when the component's window loses the focus.

 Component getComponent() (  in  java.awt.event.ComponentEvent) 

Return the component that fired the focus event.

Component getOppositeComponent()

Return the other component involved in the focus change. For a FOCUS_GAINED event, this is the component that lost the focus. For a FOCUS_LOST 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 null is returned. This method was introduced in release 1.4.

Examples That Use Focus Listeners

The following examples use focus listeners.

Example

Where Described

Notes

FocusEventDemo

This section

Reports all focus events that occur on several components to demonstrate the circumstances under which focus events are fired.

TrackFocusDemo

How to Use the Focus Subsystem (page 583)

The custom component, Picture , implements a focus listener to draw a red border around the component when it is the current focus owner.

 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net