UNPKG

epubjs

Version:

Render ePub documents in the browser, across many devices

301 lines (298 loc) 35.9 kB
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><title>Events</title><link rel="stylesheet" href="core.css" type="text/css"/><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"/></head><body><div class="sect1" title="Events"><div class="titlepage"><div><div><h1 class="title"><a id="learnjava3-CHP-16-SECT-2"/>Events</h1></div></div></div><p>We’ve spent a lot of time discussing the different kinds of objects in Swing—components, containers, and special containers such as frames and windows. Now it’s time to discuss interobject communication in detail.</p><p>Swing objects communicate by sending events. The way we talk about events—“firing” them and “handling” them—makes it sound as if they are part of some special Java language feature. But they aren’t. An event is simply an ordinary Java object that is delivered to its receiver by invoking an ordinary Java method. Everything else, however interesting, is purely convention. The entire Java event mechanism is really just a set of conventions for the kinds of descriptive objects that should be delivered; these conventions prescribe when, how, and to whom events should be delivered.</p><p>Events are sent from a single source object to one or more listeners. A listener implements prescribed event-handling methods that enable it to receive a type of event. It then registers itself with a source of that kind of event. Sometimes an adapter object may be interposed between the event source and the listener, but in any case, registration of a listener is always established before any events are delivered.</p><p>An event object is an instance of a subclass of <code class="literal">java.util.EventObject</code>; it holds information about something that’s happened to its source. The <code class="literal">EventObject</code> parent class itself serves mainly to identify event objects; the only information it contains is a reference to the event source (the object that sent the event). Components don’t normally send or receive <code class="literal">EventObject</code>s as such; they work with subclasses that provide more specific information.</p><p><a id="I_indexterm16_id788545" class="indexterm"/> <code class="literal">AWTEvent</code> is a subclass of <code class="literal">java.awt.EventObject</code>; further subclasses of <code class="literal">AWTEvent</code> provide information about specific event types. Swing has events of its own that descend directly from <code class="literal">EventObject</code>. For the most part, you’ll just be working with specific event subclasses from the AWT or Swing packages.</p><p><code class="literal">ActionEvent</code>s correspond to a decisive “action” that a user has taken with the component, such as clicking a button or pressing Enter. An <a id="I_indexterm16_id788585" class="indexterm"/><code class="literal">ActionEvent</code> carries the name of an action to be performed (the <span class="emphasis"><em>action command</em></span>) by the program. <a id="I_indexterm16_id788600" class="indexterm"/><code class="literal">MouseEvents</code> are generated when a user uses the mouse within a component’s area. They describe the state of the mouse and therefore carry such information as the <code class="literal">x</code> and <code class="literal">y</code> coordinates and the state of your mouse buttons at the time the <code class="literal">MouseEvent</code> was created.</p><p><code class="literal">ActionEvent</code> operates at a higher semantic level than <code class="literal">MouseEvent</code>: an <code class="literal">ActionEvent</code> lets us know that a component has performed its job; a <code class="literal">MouseEvent</code> simply confers a lot of information about the mouse at a given time. You could figure out that somebody clicked on a <code class="literal">JButton</code> by examining mouse events, but it is simpler to work with action events. The precise meaning of an event can also depend on the context in which it is received.</p><div class="sect2" title="Event Receivers and Listener Interfaces"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.1"/>Event Receivers and Listener Interfaces</h2></div></div></div><p><a id="idx10933" class="indexterm"/> <a id="idx10942" class="indexterm"/> <a id="idx10947" class="indexterm"/> <a id="idx10968" class="indexterm"/>An event is delivered by passing it as an argument to the receiving object’s event handler method. <code class="literal">ActionEvent</code>s, for example, are always delivered to a method called <a id="I_indexterm16_id788724" class="indexterm"/><code class="literal">actionPerformed()</code> in the receiver:</p><a id="I_16_tt985"/><pre class="programlisting"> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">actionPerformed</code><code class="o">(</code> <code class="n">ActionEvent</code> <code class="n">e</code> <code class="o">)</code> <code class="o">{</code> <code class="o">...</code> <code class="o">}</code></pre><p>For each type of event, a corresponding listener interface prescribes the method(s) it must provide to receive those events. In this case, any object that receives <code class="literal">Action</code><code class="literal">Event</code>s must implement the <a id="I_indexterm16_id788761" class="indexterm"/><code class="literal">ActionListener</code> interface:</p><a id="I_16_tt986"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">interface</code> <code class="nc">ActionListener</code> <code class="kd">extends</code> <code class="n">java</code><code class="o">.</code><code class="na">util</code><code class="o">.</code><code class="na">EventListener</code> <code class="o">{</code> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">actionPerformed</code><code class="o">(</code> <code class="n">ActionEvent</code> <code class="n">e</code> <code class="o">);</code> <code class="o">}</code></pre><p>All listener interfaces are subinterfaces of <a id="I_indexterm16_id788784" class="indexterm"/><code class="literal">java.util.EventListener</code>, which is an empty interface. It exists only to help Java-based tools such as IDEs identify listener interfaces.</p><p>Listener interfaces are required for a number of reasons. First, they help to identify objects that can receive a given type of event—they make event hookups “strongly typed.” Event listener interfaces allow us to give the event handler methods friendly, descriptive names and still make it easy for documentation, tools, and humans to recognize them in a class. Next, listener interfaces are useful because several methods can be specified for an event receiver. For example, the <a id="I_indexterm16_id788817" class="indexterm"/><code class="literal">FocusListener</code> interface contains two methods:</p><a id="I_16_tt987"/><pre class="programlisting"> <code class="kd">abstract</code> <code class="kt">void</code> <code class="nf">focusGained</code><code class="o">(</code> <code class="n">FocusEvent</code> <code class="n">e</code> <code class="o">);</code> <code class="kd">abstract</code> <code class="kt">void</code> <code class="nf">focusLost</code><code class="o">(</code> <code class="n">FocusEvent</code> <code class="n">e</code> <code class="o">);</code></pre><p>Although these methods each take a <a id="I_indexterm16_id788840" class="indexterm"/><code class="literal">FocusEvent</code> as an argument, they correspond to different reasons (contexts) for firing the event—in this case, whether the <code class="literal">FocusEvent</code> means that focus was received or lost. In this case, you could also figure out what happened by inspecting the event; all <code class="literal">AWTEvent</code>s contain a constant specifying the event’s type. But by using two methods, the <code class="literal">FocusListener</code> interface saves you the effort: if <code class="literal">focusGained()</code> is called, you know the event type was <code class="literal">FOCUS_GAINED</code>.</p><p>Similarly, the <a id="I_indexterm16_id788885" class="indexterm"/><code class="literal">MouseListener</code> interface defines five methods for receiving mouse events (and <a id="I_indexterm16_id788896" class="indexterm"/><code class="literal">MouseMotionListener</code> defines two more), each of which gives you some additional information about why the event occurred. In general, the listener interfaces group sets of related event handler methods; the method called in any given situation provides a context for the information in the event object.</p><p>There can be more than one listener interface for dealing with a particular kind of event. For example, the <code class="literal">MouseListener</code> interface describes methods for receiving <code class="literal">Mouse</code><code class="literal">Event</code>s when the mouse enters or exits an area or a mouse button is pressed or released. <code class="literal">MouseMotionListener</code> is an entirely separate interface that describes methods to get mouse events when the mouse is moved (no buttons pressed) or dragged (buttons pressed). By separating mouse events into these two categories, Java lets you be a little more selective about the circumstances under which you want to receive <code class="literal">MouseEvent</code>s. You can register as a listener for mouse events without receiving mouse motion events; because mouse motion events are extremely common, you don’t want to handle them if you don’t need to.</p><p>Two simple patterns govern the naming of Swing event listener interfaces and handler methods:</p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p>Event handler methods are public methods that return type <code class="literal">void</code> and take a single event object (a subclass of <code class="literal">java.util.EventObject</code>) as an argument.<sup>[<a id="learnjava3-CHP-16-FN-3" href="#ftn.learnjava3-CHP-16-FN-3" class="footnote">39</a>]</sup></p></li><li class="listitem"><p>Listener interfaces are subclasses of <code class="literal">java.util.EventListener</code> that are named with the suffix “Listener”—for example, <code class="literal">MouseListener</code> and <code class="literal">ActionListener</code>.</p></li></ul></div><p>These may seem obvious, but they are nonetheless important because they are our first hint of a design pattern governing how to build components that work with events.<a id="I_indexterm16_id789007" class="indexterm"/><a id="I_indexterm16_id789014" class="indexterm"/><a id="I_indexterm16_id789021" class="indexterm"/><a id="I_indexterm16_id789028" class="indexterm"/></p></div><div class="sect2" title="Event Sources"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.2"/>Event Sources</h2></div></div></div><p><a id="idx10934" class="indexterm"/> <a id="idx10949" class="indexterm"/> <a id="idx10969" class="indexterm"/>The previous section described the machinery an event receiver uses to listen for events. In this section, we’ll describe how a receiver tells an event source to send it events as they occur.</p><p>To receive events, an eligible listener must register itself with an event source. It does this by calling an “add listener” method in the event source and passing a reference to itself. (Thus, this scheme implements a <span class="emphasis"><em>callback</em></span> facility.) For example, the Swing <code class="literal">JButton</code> class is a source of <code class="literal">ActionEvent</code>s. Here’s how a <code class="literal">TheReceiver</code> object might register to receive these events:</p><a id="I_16_tt988"/><pre class="programlisting"> <code class="c1">// receiver of ActionEvents</code> <code class="kd">class</code> <code class="nc">TheReceiver</code> <code class="kd">implements</code> <code class="n">ActionListener</code> <code class="o">{</code> <code class="c1">// source of ActionEvents</code> <code class="n">JButton</code> <code class="n">theButton</code> <code class="o">=</code> <code class="k">new</code> <code class="n">JButton</code><code class="o">(</code><code class="s">"Belly"</code><code class="o">);</code> <code class="n">TheReceiver</code><code class="o">()</code> <code class="o">{</code> <code class="o">...</code> <code class="n">theButton</code><code class="o">.</code><code class="na">addActionListener</code><code class="o">(</code> <code class="k">this</code> <code class="o">);</code> <code class="o">}</code> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">actionPerformed</code><code class="o">(</code> <code class="n">ActionEvent</code> <code class="n">e</code> <code class="o">)</code> <code class="o">{</code> <code class="c1">// Belly Button pushed...</code> <code class="o">}</code></pre><p><code class="literal">TheReciever</code> makes a call to the button’s <code class="literal">addActionListener()</code> to receive <code class="literal">ActionEvent</code>s from the button when they occur. It passes the reference <code class="literal">this</code> to register itself as an <code class="literal">ActionListener</code>.</p><p>To manage its listeners, an <code class="literal">ActionEvent</code> source (like the <code class="literal">JButton</code>) always implements two methods:</p><a id="I_16_tt989"/><pre class="programlisting"> <code class="c1">// ActionEvent source</code> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">addActionListener</code><code class="o">(</code><code class="n">ActionListener</code> <code class="n">listener</code><code class="o">)</code> <code class="o">{</code> <code class="o">...</code> <code class="o">}</code> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">removeActionListener</code><code class="o">(</code><code class="n">ActionListener</code> <code class="n">listener</code><code class="o">)</code> <code class="o">{</code> <code class="o">...</code> <code class="o">}</code></pre><p>The <a id="I_indexterm16_id789176" class="indexterm"/><code class="literal">removeActionListener()</code> method removes the listener from the list so that it will not receive future events of that kind. Swing components supply implementations of both methods; normally, you won’t need to implement them yourself. It’s important to pay attention to how your application uses event sources and listeners. It’s OK to throw away an event source without removing its listeners, but it isn’t necessarily OK to throw away listeners without removing them from the source first because the event source might maintain references to them, preventing them from being garbage-collected.</p><p>You may be expecting some kind of “event source” interface listing these two methods and identifying an object as a source of this event type, but there isn’t one. There are no event source interfaces in the current conventions. If you are analyzing a class and trying to determine what events it generates, you have to look for the paired add and remove methods. For example, the presence of the <a id="I_indexterm16_id789203" class="indexterm"/><code class="literal">addActionListener()</code> and <code class="literal">removeActionListener()</code> methods define the object as a source of <code class="literal">ActionEvent</code>s. If you happen to be a human being, you can simply look at the documentation, but if the documentation isn’t available, or if you’re writing a program that needs to analyze a class (a process called <span class="emphasis"><em>reflection</em></span>), you can look for this design pattern. (The <code class="literal">java.beans.Introspector</code> utility class can do this for you.)</p><p>A source of <code class="literal">FooEvent</code> events for the <code class="literal">FooListener</code> interface must implement a pair of add/remove methods:</p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p><code class="literal">addFooListener(FooListener</code> <em class="replaceable"><code>listener</code></em> <code class="literal">)</code></p></li><li class="listitem"><p><code class="literal">removeFooListener(FooListener</code> <em class="replaceable"><code>listener</code></em> <code class="literal">)</code></p></li></ul></div><p>If an event source can support only one event listener (unicast delivery), the add listener method can throw the <a id="I_indexterm16_id789287" class="indexterm"/><code class="literal">java.util.TooManyListenersException</code>.</p><p>What do all the naming patterns up to this point accomplish? For one thing, they make it possible for automated tools and integrated development environments to divine sources of particular events. Tools that work with JavaBeans will use the Java reflection and introspection APIs to search for these kinds of design patterns and identify the events that can be fired by a component.</p><p>At a more concrete level, it also means that event hookups are strongly typed, just like the rest of Java. So it’s impossible to accidentally hook up the wrong kind of components; for example, you can’t register to receive <code class="literal">ItemEvent</code>s from a <code class="literal">JButton</code> because a button doesn’t have an <code class="literal">addItemListener()</code> method. Java knows at compile time what types of events can be delivered to whom.<a id="I_indexterm16_id789328" class="indexterm"/><a id="I_indexterm16_id789335" class="indexterm"/><a id="I_indexterm16_id789342" class="indexterm"/></p></div><div class="sect2" title="Event Delivery"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.3"/>Event Delivery</h2></div></div></div><p><a id="idx10930" class="indexterm"/> <a id="I_indexterm16_id789368" class="indexterm"/>Swing and AWT events are multicast; every event is associated with a single source but can be delivered to any number of receivers. When an event is fired, it is delivered individually to each listener on the list (see <a class="xref" href="ch16s02.html#learnjava3-CHP-16-FIG-3" title="Figure 16-3. Event delivery">Figure 16-3</a>).</p><div class="figure"><a id="learnjava3-CHP-16-FIG-3"/><div class="figure-contents"><div class="mediaobject"><a id="I_16_tt990"/><img src="httpatomoreillycomsourceoreillyimages1707650.png" alt="Event delivery"/></div></div><p class="title">Figure 16-3. Event delivery</p></div><p>There are no guarantees about the order in which events are delivered. Nor are there any guarantees about what happens if you register yourself more than once with an event source; you may or may not get the event more than once. Similarly, you should assume that every listener receives the same event data. In general, events are immutable; they can’t be changed by their listeners.</p><p>To be complete, we could say that event delivery is synchronous with respect to the event source, but that is because the event delivery is really just the invocation of a normal Java method. The source of the event calls the handler method of each listener. However, listeners shouldn’t assume that all the events will be sent in the same thread unless they are AWT/Swing events, which are always sent serially by a global event dispatcher thread.</p></div><div class="sect2" title="Event Types"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.4"/>Event Types</h2></div></div></div><p><a id="idx10935" class="indexterm"/> <a id="idx10970" class="indexterm"/>All the events used by Swing GUI components are subclasses of <a id="I_indexterm16_id789458" class="indexterm"/><code class="literal">java.util.EventObject</code>. You can use or subclass any of the <code class="literal">EventObject</code> types for use in your own components. We describe the important event types here.</p><p>The events and listeners that are used by Swing fall into two packages: <a id="I_indexterm16_id789479" class="indexterm"/><code class="literal">java.awt.event</code> and <a id="I_indexterm16_id789489" class="indexterm"/><code class="literal">javax.swing.event</code>. As we’ve discussed, the structure of components has changed significantly between AWT and Swing. The event mechanism, however, is fundamentally the same, so the events and listeners in <code class="literal">java.awt.event</code> are used by Swing components. In addition, Swing has added event types and listeners in the package <code class="literal">javax.swing.event</code>.</p><p><code class="literal">java.awt.event.ComponentEvent</code> is the base class for events that can be fired by any component. This includes events that provide notification when a component changes its dimensions or visibility, as well as the other event types for mouse operations and keypresses. <code class="literal">ContainerEvent</code>s are fired by containers when components are added or removed.<a id="I_indexterm16_id789530" class="indexterm"/></p></div><div class="sect2" title="The java.awt.event.InputEvent Class"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.5"/>The java.awt.event.InputEvent Class</h2></div></div></div><p><a id="I_indexterm16_id789545" class="indexterm"/> <a id="idx10940" class="indexterm"/> <a id="I_indexterm16_id789564" class="indexterm"/> <code class="literal">MouseEvent</code>s, which track the state of the mouse, and <code class="literal">KeyEvent</code>s, which are fired when the user uses the keyboard, are kinds of <code class="literal">java.awt.event.InputEvent</code>s. When the user presses a key or moves the mouse within a component’s area, the events are generated with that component identified as the source.</p><p>Input events and GUI events are processed in a special event queue that is managed by Swing. This gives Swing control over how all its events are delivered. First, under some circumstances, a sequence of the same type of event may be compressed into a single event. This is done to make some event types more efficient—in particular, mouse events and some special internal events used to control repainting. Perhaps more important to us, input events are delivered with extra information that lets listeners decide if the component itself should act on the event.</p></div><div class="sect2" title="Mouse and Key Modifiers on InputEvents"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.6"/>Mouse and Key Modifiers on InputEvents</h2></div></div></div><p><a id="idx10932" class="indexterm"/> <a id="idx10967" class="indexterm"/> <code class="literal">InputEvent</code>s come with a set of flags for special modifiers. These let you detect whether the Shift, Control, or Alt keys were held down during a mouse button or keypress, and, in the case of a mouse button press, distinguish which mouse button was involved. The following are the flag values contained in <code class="literal">java.awt.event.InputEvent</code>:</p><div class="variablelist"><dl><dt><span class="term"><code class="literal">SHIFT_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789665" class="indexterm"/>Shift key with event</p></dd><dt><span class="term"><code class="literal">CTRL_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789681" class="indexterm"/>Control key with event</p></dd><dt><span class="term"><code class="literal">ALT_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789696" class="indexterm"/>Windows Alt key or Mac Option/Alt with event; equivalent to <code class="literal">BUTTON2_MASK</code></p></dd><dt><span class="term"><code class="literal">META_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789716" class="indexterm"/>Mac Command key with event; equivalent to <code class="literal">BUTTON3_MASK</code></p></dd><dt><span class="term"><code class="literal">BUTTON1_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789735" class="indexterm"/>Mouse Button 1</p></dd><dt><span class="term"><code class="literal">BUTTON2_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789750" class="indexterm"/>Mouse Button 2; equivalent to <code class="literal">ALT_MASK</code></p></dd><dt><span class="term"><code class="literal">BUTTON3_MASK</code></span></dt><dd><p><a id="I_indexterm16_id789770" class="indexterm"/>Mouse Button 3; equivalent to <code class="literal">META_MASK</code></p></dd></dl></div><p>To check for one or more flags, evaluate the bitwise AND of the complete set of modifiers and the flag or flags you’re interested in. The complete set of modifiers involved in the event is returned by the <code class="literal">InputEvent</code>’s <a id="I_indexterm16_id789792" class="indexterm"/><code class="literal">getModifiers()</code> method:</p><a id="I_16_tt991"/><pre class="programlisting"> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">mousePressed</code> <code class="o">(</code><code class="n">MouseEvent</code> <code class="n">e</code><code class="o">)</code> <code class="o">{</code> <code class="kt">int</code> <code class="n">mods</code> <code class="o">=</code> <code class="n">e</code><code class="o">.</code><code class="na">getModifiers</code><code class="o">();</code> <code class="k">if</code> <code class="o">((</code><code class="n">mods</code> <code class="o">&amp;</code> <code class="n">InputEvent</code><code class="o">.</code><code class="na">SHIFT_MASK</code><code class="o">)</code> <code class="o">!=</code> <code class="mi">0</code><code class="o">)</code> <code class="o">{</code> <code class="c1">// shifted Mouse Button press</code> <code class="o">}</code> <code class="o">}</code></pre><p>The three <code class="literal">BUTTON</code> flags can determine which mouse button was pressed on a two- or three-button mouse. <code class="literal">BUTTON2_MASK</code> is equivalent to <code class="literal">ALT_MASK</code>, and <code class="literal">BUTTON3_MASK</code> is equivalent to <code class="literal">META_MASK</code>. This means that pushing the second mouse button is equivalent to pressing the first (or only) button with the Alt key depressed, and the third button is equivalent to the first with the “Meta” key depressed. These provide some minimal portability even for systems that don’t provide multibutton mice. However, for the most common uses of these buttons—pop-up menus—you don’t have to write explicit code; Swing provides special support that automatically maps to the correct gesture in each environment (see the <code class="literal">PopupMenu</code> class in <a class="xref" href="ch17.html" title="Chapter 17. Using Swing Components">Chapter 17</a>).</p><div class="sect3" title="Mouse-wheel events"><div class="titlepage"><div><div><h3 class="title"><a id="learnjava3-CHP-16-SECT-2.6.1"/>Mouse-wheel events</h3></div></div></div><p><a id="I_indexterm16_id789867" class="indexterm"/> <a id="idx10943" class="indexterm"/> <a id="I_indexterm16_id789887" class="indexterm"/>Java 1.4 added support for the mouse wheel, which is a scrolling device in place of a middle mouse button. By default, Swing handles mouse-wheel movement for scrollable components, so you should not have to write explicit code to handle this. Mouse-wheel events are handled a little differently from other events because the conventions for using the mouse wheel don’t always require the mouse to be over a scrolling component. If the immediate target component of a mouse-wheel event is not registered to receive it, a search is made for the first enclosing container that wants to consume the event. This allows components enclosed in <a id="I_indexterm16_id789909" class="indexterm"/><code class="literal">ScrollPane</code>s to operate as expected.</p><p>If you wish to explicitly handle mouse-wheel events, you can register to receive them using the <a id="I_indexterm16_id789924" class="indexterm"/><code class="literal">MouseWheelListener</code> interface shown in <a class="xref" href="ch16s03.html#learnjava3-CHP-16-TABLE-1" title="Table 16-1. Swing component and container events">Table 16-1</a> in the next section. Mouse-wheel events encapsulate information about the amount of scrolling and the type of scroll unit, which on most systems may be configured externally to be fine-grained scroll units or large blocks. If you want a physical measure of how far the wheel was turned, you can get that with the <a id="I_indexterm16_id789943" class="indexterm"/><code class="literal">getWheelRotation()</code> method, which returns a number of clicks.<a id="I_indexterm16_id789954" class="indexterm"/><a id="I_indexterm16_id789961" class="indexterm"/></p></div></div><div class="sect2" title="Focus Events"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-16-SECT-2.7"/>Focus Events</h2></div></div></div><p><a id="idx10931" class="indexterm"/> <a id="idx10937" class="indexterm"/> <a id="idx10966" class="indexterm"/>As we mentioned earlier, focus handling is largely done automatically in Swing applications and we’ll discuss it further in <a class="xref" href="ch18.html" title="Chapter 18. More Swing Components">Chapter 18</a>. However, understanding how focus events are handled will help you understand and customize components.</p><p>As we described, a component can make itself eligible to receive focus using the <code class="literal">JComponent setFocusable()</code> method (Windows may use <code class="literal">setFocusableWindowState()</code>). A component normally receives focus when the user clicks on it with the mouse. It can also programmatically request focus using the <a id="I_indexterm16_id790036" class="indexterm"/><code class="literal">requestFocus()</code> or <a id="I_indexterm16_id790047" class="indexterm"/><code class="literal">requestFocusInWindow()</code> methods. The <code class="literal">requestFocusInWindow()</code> method acts just like <code class="literal">requestFocus()</code> except that it does not ask for transfer across windows. (There are currently limitations on some platforms that prevent focus transfer from native applications to Java applications, so using <code class="literal">requestFocusInWindow()</code> guarantees portability by adding this restriction.)</p><p>Although a component can request focus explicitly, the only way to verify when a component has received or lost focus is by using the <a id="I_indexterm16_id790080" class="indexterm"/><code class="literal">FocusListener</code> interface (see Tables <a class="xref" href="ch16s03.html#learnjava3-CHP-16-TABLE-1" title="Table 16-1. Swing component and container events">16-1</a> and <a class="xref" href="ch16s03.html#learnjava3-CHP-16-TABLE-2" title="Table 16-2. Component-specific swing events">16-2</a>). You can use this interface to customize the behavior of your component when it is ready for input (e.g., the <code class="literal">TextField</code>’s blinking cursor). Also, input components often respond to the loss of focus by committing their changes. For example, <code class="literal">JTextField</code>s and other components can be arranged to validate themselves when the user attempts to move to a new field and to prevent the focus change until the field is valid (as we’ll see in <a class="xref" href="ch18.html" title="Chapter 18. More Swing Components">Chapter 18</a>).</p><p>Assuming that there is currently no focus, the following sequence of events happens when a component receives focus:</p><a id="I_16_tt992"/><pre class="programlisting"> <code class="n">WINDOW_ACTIVATED</code> <code class="n">WINDOW_GAINED_FOCUS</code> <code class="n">FOCUS_GAINED</code></pre><p>The first two are <code class="literal">WindowEvent</code>s delivered to the component’s containing <code class="literal">Window</code>, and the third is a <code class="literal">FocusEvent</code> that is sent to the component itself. If a component in another window subsequently receives focus, the following complementary sequence will occur:</p><a id="I_16_tt993"/><pre class="programlisting"> <code class="n">FOCUS_LOST</code> <code class="n">WINDOW_FOCUS_LOST</code> <code class="n">WINDOW_DEACTIVATED</code></pre><p>These events carry a certain amount of context with them. The receiving component can determine the component and window from which the focus is being transferred. The yielding component and window are called “opposites” and are available with the <code class="literal">FocusEvent</code><a id="I_indexterm16_id790178" class="indexterm"/><code class="literal">getOppositeComponent()</code> and <code class="literal">WindowEvent getOppositeWindow()</code> methods. If the opposite is part of a native non-Java application, then these values may be <code class="literal">null</code>.</p><p>Focus gained and lost events may also be marked as “temporary,” as determined by the <code class="literal">FocusEvent isTemporary()</code> method. The concept of a temporary focus change is used for components such as pop-up menus, scrollbars, and window manipulation where control is expected to return to the primary component later. The distinction is made for components to “commit” or validate data upon losing focus. No commit should happen on a temporary loss of focus.<a id="I_indexterm16_id790217" class="indexterm"/><a id="I_indexterm16_id790224" class="indexterm"/><a id="I_indexterm16_id790231" class="indexterm"/></p></div><div class="footnotes"><br/><hr/><div class="footnote"><p><sup>[<a id="ftn.learnjava3-CHP-16-FN-3" href="#learnjava3-CHP-16-FN-3" class="para">39</a>] </sup>This rule is not complete. The JavaBeans conventions (see <a class="xref" href="ch22.html" title="Chapter 22. JavaBeans">Chapter 22</a>) allows event handler methods to take additional arguments when absolutely necessary and also to throw checked exceptions.</p></div></div></div></body></html>