Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Chapter 2. (Introduction) Swing Mechanics. Easy for reading, Click here!

Custom Search
Chapter 2. (Introduction) Swing Mechanics. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 12/14 



Previous Page Previous Page (11/14) - Next Page (13/14) Next Page
Subpages: 1. JComponent properties, size, and positioning 
2.  Event handling and dispatching 
3. Multithreading
4. Timers
5. AppContext service
6. Inside Timers & the TimerQueue
7. JavaBeans architecture
8. Fonts, Colors, Graphics and text
9. Using the Graphics clipping area
10. Graphics debugging
11. Painting and validation
12. Focus Management
13. Keyboard input, KeyStrokes, and Actions
14. SwingUtilities

2.12  Focus Management

When Swing components are placed in a Swing container, the route of keyboard focus is, by default, left to right and top to bottom. This route is referred to as a focus cycle, and moving focus from one component to the next in a cycle is accomplished using the TAB key or CTRL-TAB. To move in the reverse direction through a cycle we use SHIFT-TAB or CTRL-SHIFT-TAB. This cycle is controlled by an instance of the abstract FocusManager class.

FocusManager relies on five JComponent properties of each component to tell it how to treat each component when the current focus reaches or leaves it:

focusCycleRoot: this specifies whether or not the component contains a focus cycle of its own. If it contains a focus cycle, focus will enter that component and loop through its focus cycle until it is manually or programatically moved out of that component. By default this property is false (for most components), and it cannot be assigned with a typical setXX() accessor. It can only be changed through overriding the isFocusCycleRoot() method and returning the appropriate boolean value.

managingFocus: this specifies whether or not KeyEvents corresponding to a focus change will be sent to the component itself or intercepted and devoured by the FocusManager. By default this property is false (for most components), and it cannot be assigned with a typical setXX() accessor. It can only be changed through overriding the isManagingFocus() method and returning the appropriate boolean value.

focusTraversable: this specifies whether or not focus can be transfered to the component by the FocusManager due to a focus shift in the focus cycle. By default this property is true (for most components), and it cannot be assigned with a typical setXX() accessor. It can only be changed through overriding the isFocusTraversable() method and returning the appropriate boolean value. (Note that when focus reaches a component through a mouse click its requestFocus() method is called. By overriding requestFocus() we can respond to focus requests on a component-specific basis.)

requestFocusEnabled: this specifies whether or not a mouse click will give focus to that component. This does not affect how the FocusManager works, which will continue to transfer focus to the component as part of the focus cycle. By default this property is true (for most components), and it can be assigned with JComponent's setRequestFocusEnabled() method.

nextFocusableComponent: this specifies the component to transfer focus to when the TAB key is pressed. By default this is set to null, as focus traversal is handled for us by a default FocusManager service. Assigning a component as the nextFocusableComponent will overpower FocusManager's focus traversal mechanism. This is done by passing the component to JComponent's setNextFocusableComponent() method.

2.12.1  FocusManager

abstract class javax.swing.FocusManager

This abstract class defines the responsibility of determining how focus moves from one component to another. FocusManager is a service class whose shared instance is stored in AppContext's service table (see 2.5). To access the FocusManager we use its static getCurrentManager() method. To assign a new FocusManager we us the static setCurrentManager() method. We can disable the current FocusManager service using the static disableFocusManager() method, and we can check whether it is enabled or not at any given point using the static isFocusManagerEnabled() method.

The following three abstract methods must be defined by sub-classes:

focusNextComponent(Component aComponent): should be called to shift focus to the next component in the focus cycle whose focusTraversable property is true.

focusPreviousComponent(Component aComponent): should be called to shift focus to the previous focusable component in the focus cycle whoe focusTraversable property is true.

processKeyEvent(Component focusedComponent, KeyEvent anEvent): should be called to either consume a KeyEvent sent to the given component, or allow it to pass through and be processed by that component itself. This method is normally used to determine whether a key press corresponds to a shift in focus. If this is determined to be the case, the KeyEvent is normally consumed and focus is moved forward or backward using the focusNextComponent() or focusPreviousComponent() methods respectively.

Note: "FocusManager will receive KEY_PRESSED, KEY_RELEASED and KEY_TYPED key events. If one event is consumed, all other events should be consumed."API

2.12.2  DefaultFocusManager

class javax.swing.DefaultFocusManager

DefaultFocusManager extends FocusManager and defines the three required methods as well as several additional methods. The most significant method in this class is compareTabOrder(), which takes two Components as parameters and determines first which component is located closer to the top of the container acting as their focus cycle root. If they are both located at the same height this method will determine which is left-most. A value of true will be returned if the first component passed in should be given focus before the second. Otherwise false will be returned.

The focusNextComponent() and focusPreviousComponent() methods shift focus as expected, and the getComponentBefore() and getComponentAfter() methods are defined to return the previous or next component, respectively, that will receive the focus after a given component in the focus cycle. The getFirstComponent() and getLastComponent() methods return the first and last component to receive focus in a given container's focus cycle.

The processKeyEvent() method intercepts KeyEvents sent to the currently focused component. If these events correspond to a shift in focus (i.e. TAB, CTRL-TAB, SHIFT-TAB, and SHIFT-CTRL-TAB) they are consumed and the focus is changed accordingly. Otherwise these events are sent to the component for processing (see section 2.13). Note that the FocusManager always has first crack at keyboard events.

Note: By default, CTRL-TAB and SHIFT-CTRL-TAB can be used to shift focus out of text components. TAB and SHIFT-TAB will move the caret instead (see chapters 11 and 19).

2.12.3  Listening for focus changes

As with AWT components, we can listen for focus changes on a component by attaching an instance of the java.awt.FocusListener interface. FocusListener defines two methods, each of which take a java.awt.FocusEvent instance as parameter:

focusGained(FocusEvent e): this method receives a FocusEvent when focus is given to a component this listener is attached to.

focusLost(FocusEvent e): this method receives a FocusEvent when focus is removed from a component this listener is attached to.

FocusEvent extends java.awt.ComponentEvent and defines, among others, the FOCUS_LOST and FOCUS_GAINED ids to distinguish between its two event types. A FOCUS_LOST event will occur corresponding to the temporary or permanent loss of focus. Temporary loss occurs when another app or window is given focus. When focus returns to this window, the component that originally lost the focus will once again gain the current focus, and a FOCUS_GAINED event will be dispatched at that time. Permanent focus loss occurs when the focus is moved by either clicking on another component in the same window, programmatically invoking requestFocus() on another component, or dispatching of any KeyEvents that cause a focus change when sent to the current FocusManager's processKeyEvent() method. As expected, we can attach and remove FocusListener implementations to any Swing component using Component's addFocusListener() and removeFocusListener() methods respectively.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy